#!/usr/bin/env python3.12
"""
Mark a single site as implement-in-progress (i) in REGISTRY.
Called by subagent at start of implementation work for ONE site.
Exit codes: 0=success, 2=input error, 3=implementation already exists
"""
from __future__ import annotations

import argparse
import datetime
import fcntl
import pathlib


def get_current_status(registry: pathlib.Path, domain: str) -> str | None:
    """Get current status for a domain from REGISTRY."""
    if not registry.exists():
        return None
    for line in registry.read_text().splitlines():
        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:
                return cols[3]
    return None


def find_site_dir(root: pathlib.Path, domain: str) -> pathlib.Path | None:
    """Find site directory for domain (e.g., sites/domain-v1)."""
    sites_dir = root / "sites"
    if not sites_dir.exists():
        return None
    for d in sites_dir.iterdir():
        if d.is_dir() and d.name.startswith(f"{domain}-v"):
            return d
    return None


def check_implementation_exists(site_dir: pathlib.Path) -> bool:
    """Check if implementation files exist (index.html, styles.css, script.js)."""
    index_file = site_dir / "index.html"
    return index_file.exists() and index_file.stat().st_size > 0


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 main() -> int:
    parser = argparse.ArgumentParser(description="Mark site as implement-in-progress (i)")
    parser.add_argument("domain", help="Domain to mark (e.g., example.com)")
    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"

    # Pre-check: if status is not O or i, check if implementation already exists
    current_status = get_current_status(registry, args.domain)
    if current_status and current_status not in ("O", "i"):
        site_dir = find_site_dir(root, args.domain)
        if site_dir and check_implementation_exists(site_dir):
            print(f"WARN:implementation_exists:{args.domain}:status={current_status}:path={site_dir / 'index.html'}")
            print("Implementation already exists. Skipping implement phase.")
            return 3

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


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