#!/usr/bin/env python3
"""Audit module seed JSON files for external Kaindl download URLs."""

from __future__ import annotations

import json
import re
from pathlib import Path
from typing import TypedDict

PROJECT_ROOT = Path(__file__).resolve().parents[2]
DATA_ROOT = PROJECT_ROOT / "web/modules/custom"
OUTPUT_PATH = PROJECT_ROOT / ".agent/evidence/external-downloads-audit.json"

DOWNLOAD_URL_RE = re.compile(
    r"https?://(?:www\.)?kaindl\.com/[^\s\"'<>)]*?\.(?:pdf|doc|docx|xls|xlsx|zip)(?:\?[^\s\"'<>)]*)?",
    re.IGNORECASE,
)


class FileFinding(TypedDict):
    count: int
    urls: list[str]


class ModuleFinding(TypedDict):
    count: int
    files: dict[str, FileFinding]


def module_data_files() -> list[Path]:
    """Return custom-module JSON seed files below each module's data directory."""
    if not DATA_ROOT.is_dir():
        return []

    files: list[Path] = []
    for module_dir in sorted(DATA_ROOT.iterdir()):
        data_dir = module_dir / "data"
        if not data_dir.is_dir():
            continue
        files.extend(sorted(data_dir.glob("*.json")))
    return files


def module_name(path: Path) -> str:
    """Extract the custom module name from a module data file path."""
    relative = path.relative_to(DATA_ROOT)
    return relative.parts[0]


def main() -> int:
    findings: dict[str, ModuleFinding] = {}
    total_urls = 0
    scanned_files = module_data_files()

    for path in scanned_files:
        text = path.read_text(encoding="utf-8")
        urls = sorted(set(DOWNLOAD_URL_RE.findall(text)))
        if not urls:
            continue

        module = module_name(path)
        module_findings = findings.setdefault(module, {"count": 0, "files": {}})
        relative_path = str(path.relative_to(PROJECT_ROOT))
        module_findings["files"][relative_path] = {
            "count": len(urls),
            "urls": urls,
        }
        module_findings["count"] += len(urls)
        total_urls += len(urls)

    payload = {
        "scanned_files": [
            str(path.relative_to(PROJECT_ROOT)) for path in scanned_files
        ],
        "total_external_download_urls": total_urls,
        "modules": findings,
    }

    OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
    _ = OUTPUT_PATH.write_text(
        json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
    )

    print(f"scanned_files={len(scanned_files)} external_download_urls={total_urls}")
    print(f"evidence={OUTPUT_PATH.relative_to(PROJECT_ROOT)}")
    return 0


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