from __future__ import annotations

import json
from pathlib import Path

import yaml


ROOT = Path(__file__).resolve().parents[1]


def read_yaml(path: Path) -> dict:
    with path.open("r", encoding="utf-8") as handle:
        data = yaml.safe_load(handle)
    return data if isinstance(data, dict) else {}


def count_jsonl(path: Path) -> int:
    if not path.exists():
        return 0
    return sum(1 for line in path.read_text(encoding="utf-8").splitlines() if line.strip())


def file_size(path: Path) -> int:
    return path.stat().st_size if path.exists() else 0


def main() -> int:
    manifest = read_yaml(ROOT / "plugins" / "1c" / "plugin.yaml")
    adapter = read_yaml(ROOT / "plugins" / "1c" / "adapters" / "qwen3-coder-30b-a3b-1c-lora-v1.yaml")
    registry = json.loads((ROOT / "registry" / "index.json").read_text(encoding="utf-8"))

    training_examples = ROOT / "plugins" / "1c" / "training" / "examples" / "instruction.examples.jsonl"
    generated_training = ROOT / "plugins" / "1c" / "training" / "raw" / "generated.instruction.jsonl"
    prepared_training = ROOT / "plugins" / "1c" / "training" / "prepared" / "train.chat.jsonl"
    metadata_example = ROOT / "plugins" / "1c" / "metadata" / "examples" / "metadata.example.json"

    print(f"1C plugin: {manifest.get('status')} v{manifest.get('version')}")
    print(f"Tasks: {', '.join(manifest.get('tasks') or [])}")
    print("")
    print("Models:")
    for model in registry.get("models") or []:
        tasks = model.get("task") or []
        if "1c" in tasks or any(str(task).startswith("1c") for task in tasks):
            print(f"- {model['id']} [{model['status']}] runtime={model.get('runtime')}")
    print("")
    print("Data:")
    print(f"- training examples: {count_jsonl(training_examples)}")
    print(f"- generated training examples: {count_jsonl(generated_training)}")
    print(f"- prepared training records: {count_jsonl(prepared_training)}")
    print(f"- prepared train JSONL: {file_size(prepared_training)} bytes")
    print(f"- metadata example: {file_size(metadata_example)} bytes")
    print("")
    training = adapter.get("training") or {}
    print("Training:")
    print(f"- adapter: {adapter.get('id')}")
    print(f"- status: {training.get('status')}")
    for blocker in training.get("blockers") or []:
        print(f"  - {blocker}")
    return 0


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