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" / "metadata.example.json"
DEFAULT_OUTPUT = ROOT / "plugins" / "1c" / "rag" / "sources" / "metadata.generated.md"

KIND_TITLES = {
    "catalog": "Справочник",
    "document": "Документ",
    "register": "Регистр",
    "common_module": "Общий модуль",
    "enum": "Перечисление",
    "report": "Отчет",
    "processing": "Обработка",
    "other": "Объект",
}


def load_snapshot(path: Path) -> dict:
    with path.open("r", encoding="utf-8") as handle:
        data = json.load(handle)
    if not isinstance(data, dict):
        raise ValueError("metadata snapshot must be a JSON object")
    if data.get("schema_version") != 1:
        raise ValueError("metadata snapshot schema_version must be 1")
    if not isinstance(data.get("objects"), list):
        raise ValueError("metadata snapshot objects must be a list")
    return data


def object_to_markdown(obj: dict) -> str:
    kind = obj.get("kind") or "other"
    title = KIND_TITLES.get(kind, "Объект")
    name = obj.get("name") or "БезИмени"
    synonym = obj.get("synonym")
    description = obj.get("description")

    lines = [f"## {title}: {name}", ""]
    if synonym:
        lines.extend([f"Синоним: {synonym}", ""])
    if description:
        lines.extend([description, ""])

    attributes = obj.get("attributes") or []
    if attributes:
        lines.extend(["### Реквизиты", ""])
        for attr in attributes:
            attr_name = attr.get("name") or "БезИмени"
            attr_type = attr.get("type") or "не указан"
            attr_synonym = attr.get("synonym")
            suffix = f" ({attr_synonym})" if attr_synonym else ""
            lines.append(f"- {attr_name}{suffix}: {attr_type}")
        lines.append("")

    tabular_sections = obj.get("tabular_sections") or []
    if tabular_sections:
        lines.extend(["### Табличные части", ""])
        for section in tabular_sections:
            section_name = section.get("name") or "БезИмени"
            section_synonym = section.get("synonym")
            suffix = f" ({section_synonym})" if section_synonym else ""
            lines.append(f"- {section_name}{suffix}")
            for attr in section.get("attributes") or []:
                attr_name = attr.get("name") or "БезИмени"
                attr_type = attr.get("type") or "не указан"
                lines.append(f"  - {attr_name}: {attr_type}")
        lines.append("")

    return "\n".join(lines).strip()


def snapshot_to_markdown(snapshot: dict) -> str:
    source = snapshot.get("source") or {}
    source_name = source.get("name") or "unknown"
    created_at = snapshot.get("created_at") or "unknown"

    sections = [
        "# 1C Metadata Snapshot",
        "",
        f"Источник: {source_name}",
        f"Дата снимка: {created_at}",
        "",
        "Этот файл сгенерирован из metadata snapshot и предназначен для RAG-поиска.",
        "",
    ]

    for obj in snapshot.get("objects") or []:
        sections.append(object_to_markdown(obj))
        sections.append("")

    return "\n".join(sections).strip() + "\n"


def main() -> int:
    parser = argparse.ArgumentParser(description="Convert a 1C metadata snapshot to a 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()

    snapshot = load_snapshot(args.input)
    markdown = snapshot_to_markdown(snapshot)
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(markdown, encoding="utf-8")
    print(f"Wrote RAG source to {args.output}")
    return 0


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