#!/usr/bin/env python3.12
"""
Mark all implemented sites (I) in a batch as done (Q) in REGISTRY.
Called by main agent after all subagents complete implementation.
Exit codes: 0=success, 1=no sites to mark, 2=input error
"""
from __future__ import annotations

import argparse
import datetime
import fcntl
import pathlib
from typing import List


def mark_batch_done(registry: pathlib.Path, lock_path: pathlib.Path, batch_id: str) -> List[str]:
    """Mark all I-status sites in batch as Q (done)."""
    if not registry.exists():
        print(f"ERROR:registry_not_found:{registry}")
        return []

    lock_path.parent.mkdir(parents=True, exist_ok=True)
    now = datetime.datetime.now().isoformat(timespec="seconds")
    marked: List[str] = []

    with lock_path.open("w") as lf:
        fcntl.flock(lf, fcntl.LOCK_EX)
        lines = registry.read_text().splitlines()
        new_lines = []
        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("|")]
                # cols: [Domain, Title, Theme, Status, Batch, Updated]
                if len(cols) >= 6 and cols[4] == batch_id and cols[3] == "I":
                    cols[3] = "Q"
                    cols[5] = now
                    marked.append(cols[0])
                    line = f"| {cols[0]} | {cols[1]} | {cols[2]} | {cols[3]} | {cols[4]} | {cols[5]} |"
            new_lines.append(line)
        registry.write_text("\n".join(new_lines) + "\n")
        fcntl.flock(lf, fcntl.LOCK_UN)

    return marked


def main() -> int:
    parser = argparse.ArgumentParser(description="Mark implemented sites (I) as done (Q)")
    parser.add_argument("--batch", required=True, help="Batch ID (e.g., 001)")
    parser.add_argument("--root", default=".", help="Repository root (default: .)")
    args = parser.parse_args()

    root = pathlib.Path(args.root).resolve()
    registry = root / ".smbatcher" / "REGISTRY.md"
    lock_path = root / ".smbatcher" / "REGISTRY.lock"

    marked = mark_batch_done(registry, lock_path, args.batch)
    if marked:
        print(f"OK:marked_done:{len(marked)} sites ({', '.join(marked)})")
        return 0
    else:
        print(f"FAIL:no_sites_to_mark:batch {args.batch} has no I-status sites")
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
