"""Reference gate.

Extracted from ui_clone/gate.py. Each function takes `self: "Gate"` and is
rebound onto the Gate class in `ui_clone.gates.__init__`.
"""

from __future__ import annotations

import json
from typing import TYPE_CHECKING

from .base import CheckResult

if TYPE_CHECKING:
    from .base import Gate  # noqa: F401


def _capture_error_result(self: Gate) -> CheckResult | None:
    """Surface structured capture diagnostics next to reference gate failures."""
    path = self.ref_dir / "capture-error.json"
    if not path.is_file():
        return None
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        return CheckResult(
            "capture-error.json",
            "warn",
            f"capture-error.json is present but unreadable: {exc}",
            fix=f"Inspect or regenerate {path}",
        )

    stage = str(payload.get("stage") or "unknown-stage")
    artifact = payload.get("artifact")
    message = str(payload.get("message") or "").strip()
    artifact_s = f" while writing {artifact}" if artifact else ""
    message_s = f": {message}" if message else ""
    return CheckResult(
        "capture-error.json",
        "warn",
        f"Phase 1 capture diagnostic: {stage}{artifact_s}{message_s}",
        fix=f"Inspect {path} before retrying Phase 1",
    )


def gate_reference(self: Gate) -> list[CheckResult]:
    results = []
    results.append(
        self.check_dir(
            self.ref_dir / "static" / "ref",
            "static/ref screenshots",
            min_files=5,
            fix="Run Phase 1: invoke /ui-capture <url> to capture reference screenshots",
        )
    )
    results.append(
        self.check_dir(
            self.ref_dir / "transitions" / "ref",
            "transitions/ref (transition videos)",
            min_files=1,
            fix="Run Phase 1: invoke /ui-capture <url> to capture transition videos",
        )
    )
    results.append(
        self.check_file(
            self.ref_dir / "regions.json",
            "regions.json (transition regions)",
            fix="Run Phase 1: invoke /ui-capture <url> to generate regions.json",
        )
    )
    capture_error = _capture_error_result(self)
    if capture_error is not None:
        results.append(capture_error)
    return results
