#!/usr/bin/env python3
"""Build a curated offline skill pack for dev/ops/test workflows."""

from __future__ import annotations

import datetime as dt
import json
import shutil
import sys
import tarfile
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
CONFIG = ROOT / "config" / "devops-testing-skill-selection.json"
OUT_ROOT = ROOT / "seed-skills" / "devops-testing"
REPORT = ROOT / "reports" / "devops-testing-skill-pack-report.md"
ARTIFACTS = ROOT / "artifacts"


def read_json(path: Path) -> dict:
    return json.loads(path.read_text(encoding="utf-8"))


def package_meta(skill_dir: Path) -> dict:
    package = read_json(skill_dir / "package.json")
    return {
        "name": package.get("name") or skill_dir.name,
        "version": package.get("version") or "0.1.0",
        "description": package.get("description") or "",
        "license": package.get("license") or "UNKNOWN",
        "source": package.get("source"),
    }


def copy_skill(src: Path, dst: Path) -> dict:
    if not src.is_dir():
        raise FileNotFoundError(f"Missing skill directory: {src}")
    if not (src / "package.json").is_file():
        raise FileNotFoundError(f"Missing package.json: {src}")
    if not (src / "skill.md").is_file():
        raise FileNotFoundError(f"Missing skill.md: {src}")

    if dst.exists():
        shutil.rmtree(dst)
    shutil.copytree(src, dst)
    meta = package_meta(dst)
    return meta


def main() -> int:
    config = read_json(CONFIG)

    if OUT_ROOT.exists():
        shutil.rmtree(OUT_ROOT)
    OUT_ROOT.mkdir(parents=True)
    REPORT.parent.mkdir(parents=True, exist_ok=True)
    ARTIFACTS.mkdir(parents=True, exist_ok=True)

    sources_json = []
    catalog = []
    report_lines = [
        "# Dev/Ops/Test Offline Skill Pack",
        "",
        f"Generated at: {dt.datetime.now(dt.timezone.utc).isoformat()}",
        "",
        "This pack is curated for development, operations, testing, API, database, security, and release workflows.",
        "It intentionally excludes imported skills that already matched simple static risk patterns in the GitHub import catalog.",
        "",
        "## Sources",
        "",
    ]

    total = 0
    for source in config["sources"]:
        source_name = source["source"]
        namespace = source["namespace"]
        source_out = OUT_ROOT / source_name
        source_out.mkdir(parents=True)

        source_catalog = []
        for rel_path in source["paths"]:
            src = ROOT / rel_path
            dst = source_out / src.name
            meta = copy_skill(src, dst)
            item = {
                "namespace": namespace,
                "name": meta["name"],
                "version": meta["version"],
                "description": meta["description"],
                "license": meta["license"],
                "source_path": rel_path,
                "package_dir": dst.relative_to(ROOT).as_posix(),
            }
            if meta.get("source"):
                item["source"] = meta["source"]
            catalog.append(item)
            source_catalog.append(item)
            total += 1

        sources_json.append(
            {
                "source": source_name,
                "namespace": namespace,
                "skill_count": len(source_catalog),
                "selection": source["paths"],
            }
        )
        report_lines.append(f"- `{namespace}` from `{source_name}`: {len(source_catalog)} skills")

    (OUT_ROOT / "_sources.json").write_text(json.dumps(sources_json, ensure_ascii=True, indent=2) + "\n", encoding="utf-8")
    (OUT_ROOT / "_catalog.json").write_text(json.dumps(catalog, ensure_ascii=True, indent=2) + "\n", encoding="utf-8")

    report_lines.extend(["", f"## Total", "", f"- Skills: {total}", "", "## Skills", ""])
    for item in catalog:
        report_lines.append(f"- `{item['namespace']}/{item['name']}` - {item['description']}")
    REPORT.write_text("\n".join(report_lines) + "\n", encoding="utf-8")

    date_stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%d")
    artifact = ARTIFACTS / f"devops-testing-skills-offline-{date_stamp}.tar.gz"
    with tarfile.open(artifact, "w:gz") as tf:
        tf.add(CONFIG, arcname=CONFIG.relative_to(ROOT).as_posix())
        tf.add(REPORT, arcname=REPORT.relative_to(ROOT).as_posix())
        tf.add(OUT_ROOT, arcname=OUT_ROOT.relative_to(ROOT).as_posix())

    import hashlib

    digest = hashlib.sha256(artifact.read_bytes()).hexdigest()
    (ARTIFACTS / f"{artifact.name}.sha256").write_text(f"{digest}  {artifact.name}\n", encoding="utf-8")

    print(f"Created {artifact}")
    print(f"Created {artifact}.sha256")
    print(f"Skills: {total}")
    print(f"Report: {REPORT}")
    return 0


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