#!/usr/bin/env python3
"""Build root CAS manifests for all parsed 1C extensions."""

from __future__ import annotations

import argparse
import json
from pathlib import Path

from extract_1c_extension_cas_manifest import extract_manifest


def safe_name(value: str) -> str:
    result = "".join(char if char.isalnum() or char in "-_." else "_" for char in value)
    return result[:120] or "extension"


def main() -> int:
    parser = argparse.ArgumentParser(description="Build CAS manifests for all extensions.")
    parser.add_argument("--zipped-info", type=Path, required=True)
    parser.add_argument("--cas-dir", type=Path, required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--summary", type=Path, required=True)
    args = parser.parse_args()

    zipped = json.loads(args.zipped_info.read_text(encoding="utf-8"))
    args.output_dir.mkdir(parents=True, exist_ok=True)
    items = []
    for item in zipped.get("items") or []:
        root_key = item.get("root_cas_key")
        if not root_key:
            continue
        root_path = args.cas_dir / root_key
        if not root_path.is_file():
            items.append({**item, "manifest_status": "root_cas_missing"})
            continue
        try:
            manifest = extract_manifest(root_path, args.cas_dir)
        except Exception as exc:
            items.append(
                {
                    "extension_zipped_info_file": item.get("file_name"),
                    "root_cas_key": root_key,
                    "manifest_status": "parse_error",
                    "error": str(exc),
                }
            )
            continue
        stem = safe_name(item.get("file_name", "").replace("__ExtensionZippedInfo.bin", ""))
        output_path = args.output_dir / f"{stem}-{root_key[:8]}.json"
        report = {
            "schema": "onec_extension_cas_manifest.v1",
            "extension_zipped_info": item,
            **manifest,
        }
        output_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
        items.append(
            {
                "extension_zipped_info_file": item.get("file_name"),
                "root_cas_key": root_key,
                "manifest_path": str(output_path),
                "extension_configuration_guid": manifest.get("extension_configuration_guid"),
                "declared_count": manifest.get("declared_count"),
                "entry_count": manifest.get("entry_count"),
                "missing_cas_entries": sum(1 for entry in manifest.get("entries") or [] if not entry.get("cas_exists")),
                "manifest_status": "ok",
            }
        )
    summary = {
        "schema": "onec_extension_manifests_summary.v1",
        "zipped_info": str(args.zipped_info),
        "cas_dir": str(args.cas_dir),
        "output_dir": str(args.output_dir),
        "extension_count": len(items),
        "items": items,
    }
    args.summary.parent.mkdir(parents=True, exist_ok=True)
    args.summary.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(
        json.dumps(
            {
                "summary": str(args.summary),
                "extensions": len(items),
                "ok": sum(1 for item in items if item.get("manifest_status") == "ok"),
            },
            ensure_ascii=False,
        )
    )
    return 0


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