#!/usr/bin/env python3.12
"""
Mark a single site as design-complete (D) in REGISTRY after validation.
Called by subagent at end of design 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

REQUIRED_HEADINGS = [
    "## Aesthetics and Tone",
    "## Layout Motifs and Structure",
    "## Typography and Palette",
    "## Imagery and Motifs",
    "## Prompts for Implementation",
    "## Uniqueness Notes",
]


def has_required(text: str) -> bool:
    return all(h in text for h in REQUIRED_HEADINGS)


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 design-complete (D) 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 DESIGN.md validation")
    args = parser.parse_args()

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

    # Validate DESIGN.md unless skipped
    if not args.skip_validation:
        design_path = root / "sites" / f"{args.domain}-v1" / "DESIGN.md"
        if not design_path.exists():
            print(f"ERROR:design_not_found:{design_path}")
            return 2
        text = design_path.read_text(encoding="utf-8")
        if not has_required(text):
            print(f"FAIL:missing_headings:{args.domain}")
            return 1

    if update_registry_status(registry, lock_path, args.domain, "D"):
        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())
