#!/usr/bin/env python3
"""Validate the portable juben skill package without third-party dependencies."""

from __future__ import annotations

import json
import re
import sys
from pathlib import Path


FRONTMATTER_RE = re.compile(r"\A---\s*\n(?P<body>.*?)\n---\s*\n", re.DOTALL)
LINK_RE = re.compile(r"\[[^\]]+\]\(([^)]+)\)")


def parse_simple_frontmatter(text: str) -> dict[str, str]:
    match = FRONTMATTER_RE.search(text)
    if not match:
        return {}
    result: dict[str, str] = {}
    for raw_line in match.group("body").splitlines():
        if not raw_line.strip() or raw_line.lstrip().startswith("#"):
            continue
        if ":" not in raw_line:
            continue
        key, value = raw_line.split(":", 1)
        result[key.strip()] = value.strip().strip('"\'')
    return result


def quoted_yaml_value(text: str, key: str) -> str | None:
    pattern = re.compile(rf"^\s*{re.escape(key)}:\s*([\"'])(.*?)\1\s*$", re.MULTILINE)
    match = pattern.search(text)
    return match.group(2) if match else None


def validate(root: Path) -> tuple[list[str], list[str]]:
    errors: list[str] = []
    warnings: list[str] = []
    skill_path = root / "SKILL.md"
    ui_path = root / "agents" / "openai.yaml"

    required = [skill_path, ui_path, root / "assets" / "icon.svg"]
    for path in required:
        if not path.is_file():
            errors.append(f"missing required file: {path.relative_to(root)}")

    if not skill_path.is_file():
        return errors, warnings

    skill_text = skill_path.read_text(encoding="utf-8")
    meta = parse_simple_frontmatter(skill_text)
    if meta.get("name") != "juben":
        errors.append("SKILL.md frontmatter name must equal juben")
    description = meta.get("description", "")
    if not description:
        errors.append("SKILL.md frontmatter description is missing")
    elif len(description) > 1024:
        errors.append(f"SKILL.md description exceeds 1024 characters: {len(description)}")

    for target in LINK_RE.findall(skill_text):
        if "://" in target or target.startswith("#"):
            continue
        resolved = (root / target).resolve()
        try:
            resolved.relative_to(root.resolve())
        except ValueError:
            errors.append(f"link escapes skill root: {target}")
            continue
        if not resolved.exists():
            errors.append(f"broken local link: {target}")

    if ui_path.is_file():
        ui_text = ui_path.read_text(encoding="utf-8")
        for key in ("display_name", "short_description", "default_prompt", "icon_small", "icon_large"):
            if quoted_yaml_value(ui_text, key) is None:
                errors.append(f"agents/openai.yaml requires a quoted {key}")
        prompt = quoted_yaml_value(ui_text, "default_prompt") or ""
        if "$juben" not in prompt:
            errors.append("agents/openai.yaml default_prompt must mention $juben")
        if "$direct-cinematic-story-systems" in prompt:
            errors.append("agents/openai.yaml still references the obsolete skill name")

    scripts = sorted((root / "scripts").glob("*.py"))
    if not scripts:
        warnings.append("no Python validation scripts found")
    for script in scripts:
        try:
            source = script.read_text(encoding="utf-8-sig")
            compile(source, str(script), "exec", dont_inherit=True)
        except (OSError, SyntaxError, UnicodeError) as exc:
            errors.append(f"Python compile failed for {script.name}: {exc}")

    required_refs = {
        "jingxu-compat-storyboard-runtime.md",
        "end-to-end-core-promotion-gate.md",
        "medium-firewall-screenplay-novel.md",
        "script-doctor-root-cause-runtime.md",
        "screenplay-causal-integrity-runtime.md",
        "core-task-dispatch-runtime.md",
        "content-gap-repair-contract.md",
        "character-world-performance-bridge.md",
        "shot-coverage-editing-contract.md",
        "production-feasibility-contract.md",
        "film-knowledge-router.md",
        "validation-and-release-contract.md",
        "source-evidence-ledger.md",
        "knowledge-plugin-governor.md",
        "creative-forge-liveness-contract.md",
        "two-chamber-roundtable-and-comparison.md",
        "novel-genre-writing-auxiliary.md",
        "jingyuan-longform-compatibility-contract.md",
        "longform-project-memory-runtime.md",
        "longform-preproduction-and-relationship-runtime.md",
        "novel-prose-realization-revision-runtime.md",
        "longform-recovery-sentinel-contract.md",
        "dialogue-subtext-auxiliary.md",
        "short-drama-medium-delta.md",
        "short-drama-comparison-and-feedback.md",
    }
    for name in sorted(required_refs):
        if not (root / "references" / name).is_file():
            errors.append(f"missing required optimized reference: references/{name}")

    if "SCHEMA_VALIDATED" not in skill_text or "HUMAN_REVIEWED" not in skill_text:
        errors.append("SKILL.md must distinguish schema validation from human review")
    return errors, warnings


def main() -> int:
    root = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    errors, warnings = validate(root)
    report = {
        "status": "PASS" if not errors else "FAIL",
        "root": str(root),
        "errors": errors,
        "warnings": warnings,
    }
    print(json.dumps(report, ensure_ascii=False, indent=2))
    return 0 if not errors else 1


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