from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_ROOT = ROOT / "plugins" / "1c" / "rag" / "official-docs"
PRIVATE_DIRS = ("raw", "normalized")
ALLOWED_PRIVATE_FILES = {".gitkeep"}


def check_private_artifacts(root: Path) -> dict[str, Any]:
    findings: list[dict[str, Any]] = []
    counts = {"private_files": 0, "unexpected_private_files": 0}
    for dirname in PRIVATE_DIRS:
        directory = root / dirname
        if not directory.exists():
            findings.append({"severity": "warning", "code": "missing_private_dir", "path": str(directory)})
            continue
        for path in sorted(item for item in directory.rglob("*") if item.is_file()):
            if path.name in ALLOWED_PRIVATE_FILES:
                continue
            counts["private_files"] += 1
            counts["unexpected_private_files"] += 1
            findings.append(
                {
                    "severity": "info",
                    "code": "private_artifact_present",
                    "message": "Private official documentation artifact exists locally; it must remain ignored and uncommitted.",
                    "path": str(path),
                }
            )
    return {
        "schema": "onec_official_docs_private_artifact_check.v1",
        "root": str(root),
        "passed": not any(item["severity"] == "error" for item in findings),
        "counts": counts,
        "findings": findings,
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="Check local private 1C official-doc artifacts.")
    parser.add_argument("--root", type=Path, default=DEFAULT_ROOT)
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()

    result = check_private_artifacts(args.root)
    if args.output:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"passed": result["passed"], "counts": result["counts"], "output": str(args.output) if args.output else None}, ensure_ascii=False))
    return 0 if result["passed"] else 2


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