#!/usr/bin/env python3
"""Build agent discovery metadata and one endpoint llms file per model package."""

from __future__ import annotations

import json
import pathlib

ROOT = pathlib.Path(__file__).resolve().parents[2]
TOOLKIT = pathlib.Path(__file__).resolve().parent
SOURCE = ROOT / "growth-packages/high-intent-catalog/catalog.json"
OUTPUT = TOOLKIT / "agent_catalog.json"
ENDPOINT_DIR = TOOLKIT / "endpoint-llms"
EXECUTABLE = {"seedance-2-5": "seedance-2.5"}


def build() -> dict:
    source = json.loads(SOURCE.read_text())
    models = {}
    ENDPOINT_DIR.mkdir(exist_ok=True)
    expected = set()
    for package in source["packages"]:
        slug = package["package"]
        guides = [{k: article[k] for k in ("intent", "title", "url", "raw_url", "sha256")} for article in package["articles"]]
        models[slug] = {
            "display_name": package["display_name"],
            "model_url": package["model_url"],
            "campaign_id": package["campaign_id"],
            "release_url": package["release_url"],
            "guides": guides,
            "verified_execution": slug in EXECUTABLE,
            "execution_model_id": EXECUTABLE.get(slug),
        }
        output = ENDPOINT_DIR / f"{slug}.txt"
        expected.add(output.name)
        lines = [
            f"# APIMART {package['display_name']}", "# Agent discovery record",
            f"# Updated: {source['generated_at']}", f"Model hub: {package['model_url']}",
            f"Release: {package['release_url']}",
            f"Verified execution in this toolkit: {'yes' if slug in EXECUTABLE else 'no'}",
            f"Execution model ID: {EXECUTABLE.get(slug, 'not available')}", "", "Evidence guides:",
        ]
        lines.extend(f"- {g['intent']}: {g['title']} — {g['raw_url']}" for g in guides)
        lines += ["", "Disclosure: these are observation-dated discovery records. Re-check current APIMART documentation before a paid request."]
        output.write_text("\n".join(lines) + "\n")
    for path in ENDPOINT_DIR.glob("*.txt"):
        if path.name not in expected:
            path.unlink()
    result = {
        "schema": "APIMART_AGENT_DISCOVERY_V1", "generated_at": source["generated_at"], "models": models,
        "summary": {"models": len(models), "guides": sum(len(m["guides"]) for m in models.values()), "endpoint_llms_files": len(expected), "verified_execution_models": len(set(EXECUTABLE) & set(models))},
    }
    OUTPUT.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
    return result["summary"]


if __name__ == "__main__":
    print(json.dumps(build(), sort_keys=True))
