from __future__ import annotations

import argparse
import json
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_INPUT = ROOT / "plugins" / "1c" / "metadata" / "examples" / "bsl-modules.example.json"
DEFAULT_OUTPUT = ROOT / "plugins" / "1c" / "rag" / "sources" / "bsl-modules.generated.md"


def module_to_markdown(module: dict) -> str:
    lines = [
        f"## Модуль: {module.get('module_id')}",
        "",
        f"Объект: {module.get('object_name')}",
        f"Тип объекта: {module.get('object_kind', 'не указан')}",
        f"Тип модуля: {module.get('module_type')}",
        "",
    ]
    procedures = module.get("procedures") or []
    functions = module.get("functions") or []
    if procedures:
        lines.extend(["### Процедуры", ""])
        for proc in procedures:
            export = " Экспорт" if proc.get("export") else ""
            params = ", ".join(proc.get("params") or [])
            lines.append(f"- {proc.get('name')}({params}){export}")
        lines.append("")
    if functions:
        lines.extend(["### Функции", ""])
        for func in functions:
            export = " Экспорт" if func.get("export") else ""
            params = ", ".join(func.get("params") or [])
            lines.append(f"- {func.get('name')}({params}){export}")
        lines.append("")
    refs = module.get("references") or []
    if refs:
        lines.extend(["### Ссылки", ""])
        for ref in refs:
            lines.append(f"- {ref}")
        lines.append("")
    lines.extend(["### Код", "", "```bsl", module.get("content") or "", "```"])
    return "\n".join(lines)


def main() -> int:
    parser = argparse.ArgumentParser(description="Convert 1C BSL module snapshot to Markdown RAG source.")
    parser.add_argument("--input", type=Path, default=DEFAULT_INPUT)
    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
    args = parser.parse_args()
    with args.input.open("r", encoding="utf-8") as handle:
        snapshot = json.load(handle)
    sections = [
        "# 1C BSL Module Snapshot",
        "",
        f"Источник: {(snapshot.get('source') or {}).get('name', 'unknown')}",
        f"Дата снимка: {snapshot.get('created_at', 'unknown')}",
        "",
    ]
    for module in snapshot.get("modules") or []:
        sections.append(module_to_markdown(module))
        sections.append("")
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text("\n".join(sections).strip() + "\n", encoding="utf-8")
    print(f"Wrote BSL RAG source to {args.output}")
    return 0


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