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

registry_path = pathlib.Path(sys.argv[1])
sites_raw = sys.argv[2]
now = datetime.datetime.now().isoformat(timespec="seconds")
lock_path = registry_path.parent / "REGISTRY.lock"

sites = []
for item in sites_raw.split(","):
    parts = item.split(":")
    if len(parts) < 2:
        continue
    domain, title = parts[0], parts[1]
    desc = parts[2] if len(parts) > 2 else ""
    sites.append((domain, title, desc))

header = [
    "# SMaking Sites Registry (template)\n",
    "\n",
    "| Domain | Title | Description | Status | Batch | Updated |\n",
    "|--------|-------|-------------|--------|-------|---------|\n",
]

lock_path.parent.mkdir(parents=True, exist_ok=True)
with lock_path.open("w") as lf:
    fcntl.flock(lf, fcntl.LOCK_EX)
    try:
        rows = {}
        if registry_path.exists():
            lines = registry_path.read_text().splitlines()
            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:
                        domain, title, desc, status, batch, updated = cols[:6]
                        rows[domain] = [domain, title, desc, status or "-", batch or "-", updated]

        for domain, title, desc in sites:
            if domain in rows:
                status = rows[domain][3] or "-"
                batch = rows[domain][4] or "-"
            else:
                status = "-"
                batch = "-"
            rows[domain] = [domain, title, desc, status, batch, now]

        body_lines = [f"| {r[0]} | {r[1]} | {r[2]} | {r[3]} | {r[4]} | {r[5]} |\n" for r in sorted(rows.values(), key=lambda r: r[0])]

        footer = [
            "\n",
            "Status codes: none/- → B → d → D → O → i → I → Q\n",
            "\n",
            "Notes:\n",
            "- Status \"-\" means registered but not in design batch.\n",
            "- Design phases use B/d/D; implement phases use O/i/I/Q.\n",
            "- Update timestamps on each transition.\n",
        ]

        registry_path.write_text("".join(header + body_lines + footer))
    finally:
        fcntl.flock(lf, fcntl.LOCK_UN)

if not sites:
    print("ERROR:no_sites:no valid sites to register")
    sys.exit(2)
print(f"OK:registered:{len(sites)} sites")
