#!/usr/bin/env python3
import datetime
import fcntl
import pathlib
import sys

registry_path = pathlib.Path(sys.argv[1])
lock_path = pathlib.Path(sys.argv[2])
batch_dir = pathlib.Path(sys.argv[3])
batch_id = sys.argv[4]

now = datetime.datetime.now().isoformat(timespec="seconds")

if not registry_path.exists():
    print(f"ERROR:registry_not_found:{registry_path}")
    sys.exit(2)

lock_path.parent.mkdir(parents=True, exist_ok=True)
batch_dir.mkdir(parents=True, exist_ok=True)

with lock_path.open("w") as lf:
    fcntl.flock(lf, fcntl.LOCK_EX)

    lines = registry_path.read_text().splitlines()
    new_lines = []
    locked_domains = []
    open_domains = []
    batch_found = False
    batch_statuses = {}

    for line in lines:
        if line.startswith("|") and "Domain" not in line and "--------" not in line:
            cols = [c.strip() for c in line.strip("|").split("|")]
            if len(cols) >= 6 and cols[4] == batch_id:
                batch_found = True
                status = cols[3]
                batch_statuses[status] = batch_statuses.get(status, 0) + 1
                if status == "D":
                    cols[3] = "O"
                    cols[5] = now
                    locked_domains.append(cols[0])
                    line = f"| {cols[0]} | {cols[1]} | {cols[2]} | {cols[3]} | {cols[4]} | {cols[5]} |"
                elif status in {"O", "i"}:
                    open_domains.append(cols[0])
        new_lines.append(line)

    if not batch_found:
        fcntl.flock(lf, fcntl.LOCK_UN)
        print(f"FAIL:batch_not_found:{batch_id}")
        sys.exit(1)

    if locked_domains:
        registry_path.write_text("\n".join(new_lines) + "\n")

    tracker = batch_dir / f"batch-{batch_id}-implement.md"
    if not tracker.exists():
        tracker.write_text(
            "# Implementation Batch {bid}\n"
            "**Created**: {now}\n"
            "**Phase**: implement\n\n"
            "| Directory | Domain | Status | Worker | Start | End | Notes |\n"
            "|-----------|--------|--------|--------|-------|-----|-------|\n".format(
                bid=batch_id, now=now
            )
        )

    if locked_domains:
        with tracker.open("a", encoding="utf-8") as th:
            for d in locked_domains:
                th.write(f"| {d}-v1 | {d} | O | - | - | - | Locked |\n")

    fcntl.flock(lf, fcntl.LOCK_UN)

if locked_domains:
    print(f"OK:locked:{len(locked_domains)} domains ({' '.join(locked_domains)})")
elif open_domains:
    print(f"OK:already_open:{len(open_domains)} domains ({' '.join(open_domains)})")
else:
    status_list = ",".join(sorted(batch_statuses.keys()))
    print(f"FAIL:no_domains:batch {batch_id} has no D/O/i domains to lock (statuses={status_list})")
    sys.exit(1)
