#!/usr/bin/env python3
"""Build and validate the catalog for deployment."""

import hashlib
import json
import sys
from datetime import datetime, timezone
from pathlib import Path

CATALOG_PATH = Path("catalog/servers.json")


def validate_catalog(data: dict) -> list[str]:
    """Validate catalog structure. Returns list of errors."""
    errors = []

    if "version" not in data:
        errors.append("Missing 'version' field")
    if "servers" not in data:
        errors.append("Missing 'servers' field")
        return errors

    seen_ids = set()
    for i, server in enumerate(data["servers"]):
        prefix = f"servers[{i}]"
        if "id" not in server:
            errors.append(f"{prefix}: missing 'id'")
        elif server["id"] in seen_ids:
            errors.append(f"{prefix}: duplicate id '{server['id']}'")
        else:
            seen_ids.add(server["id"])

        if "name" not in server:
            errors.append(f"{prefix}: missing 'name'")
        if "command" not in server:
            errors.append(f"{prefix}: missing 'command'")
        if "category" not in server:
            errors.append(f"{prefix}: missing 'category'")

        for j, opt in enumerate(server.get("config_options", [])):
            opt_prefix = f"{prefix}.config_options[{j}]"
            if "name" not in opt:
                errors.append(f"{opt_prefix}: missing 'name'")
            if "type" not in opt:
                errors.append(f"{opt_prefix}: missing 'type'")

    return errors


def main():
    if not CATALOG_PATH.exists():
        print(f"ERROR: {CATALOG_PATH} not found")
        sys.exit(1)

    with open(CATALOG_PATH) as f:
        data = json.load(f)

    # Validate
    errors = validate_catalog(data)
    if errors:
        print("Catalog validation FAILED:")
        for e in errors:
            print(f"  - {e}")
        sys.exit(1)

    # Stamp the updated_at
    data["updated_at"] = datetime.now(timezone.utc).isoformat()

    # Write back
    with open(CATALOG_PATH, "w") as f:
        json.dump(data, f, indent=2)

    # Compute checksum
    raw = json.dumps(data, sort_keys=True)
    checksum = hashlib.sha256(raw.encode()).hexdigest()

    server_count = len(data["servers"])
    version = data["version"]

    print(f"Catalog v{version}: {server_count} servers, sha256:{checksum[:16]}...")
    print("Validation passed.")


if __name__ == "__main__":
    main()
