#!/usr/bin/env python3.12
"""
Mark a single site as implement-complete (I) in REGISTRY after validation.
Called by subagent at end of implementation work for ONE site.
Exit codes: 0=success, 1=validation failed, 2=input error
"""
from __future__ import annotations

import argparse
import datetime
import fcntl
import pathlib
import subprocess


def update_registry_status(registry: pathlib.Path, lock_path: pathlib.Path, domain: str, status: str) -> bool:
    """Update status for a single domain in REGISTRY with locking."""
    if not registry.exists():
        print(f"ERROR:registry_not_found:{registry}")
        return False

    lock_path.parent.mkdir(parents=True, exist_ok=True)
    now = datetime.datetime.now().isoformat(timespec="seconds")
    found = False

    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("|")]
                if len(cols) >= 6 and cols[0] == domain:
                    cols[3] = status
                    cols[5] = now
                    line = f"| {cols[0]} | {cols[1]} | {cols[2]} | {cols[3]} | {cols[4]} | {cols[5]} |"
                    found = True
            new_lines.append(line)
        registry.write_text("\n".join(new_lines) + "\n")
        fcntl.flock(lf, fcntl.LOCK_UN)

    return found


def validate_site(root: pathlib.Path, domain: str) -> bool:
    """Run validation checks on implemented site."""
    site_dir = root / "sites" / f"{domain}-v1"

    # Check required files exist
    required = ["index.html", "styles.css", "script.js"]
    for f in required:
        if not (site_dir / f).exists():
            print(f"FAIL:missing_file:{f}")
            return False

    # Run check-outputs.py
    try:
        result = subprocess.run(
            ["uv", "run", "python3.12", str(root / "tools/implement/check-outputs.py"), str(site_dir)],
            check=True,
            capture_output=True,
            text=True,
        )
        # Print stdout from check-outputs.py
        if result.stdout.strip():
            print(result.stdout.strip())
    except subprocess.CalledProcessError as e:
        print(f"FAIL:check_outputs_failed:{e.stdout.strip() if e.stdout else e.stderr.strip()}")
        return False

    return True


def main() -> int:
    parser = argparse.ArgumentParser(description="Mark site as implement-complete (I) after validation")
    parser.add_argument("domain", help="Domain to mark (e.g., example.com)")
    parser.add_argument("--root", default=".", help="Repository root (default: .)")
    parser.add_argument("--skip-validation", action="store_true", help="Skip implementation validation")
    args = parser.parse_args()

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

    # Validate implementation unless skipped
    if not args.skip_validation:
        if not validate_site(root, args.domain):
            print(f"FAIL:validation_failed:{args.domain}")
            return 1

    if update_registry_status(registry, lock_path, args.domain, "I"):
        print(f"OK:marked_complete:{args.domain}")
        return 0
    else:
        print(f"ERROR:domain_not_found:{args.domain}")
        return 2


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