#!/usr/bin/env python3
"""
Parse panel configuration based on YAML files for an architecture.
Usage:
    python parse_config_template.py <dir_path> [output_file.yaml] [--latest-arch ARCH]
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path
from typing import Any, Optional

try:
    from . import utils as cm_utils
except Exception:
    repo_root = Path(__file__).resolve().parents[1]
    if str(repo_root) not in sys.path:
        sys.path.insert(0, str(repo_root))
    try:
        import config_management.utils as cm_utils  # type: ignore
    except Exception:
        import utils as cm_utils  # type: ignore

AUTOGEN_TEXT = (
    "# AUTOGENERATED FILE. Only edit for testing purposes, not for development. "
    "Generated by tools/config_management/parse_config_template.py\n"
)


def parse_panel_config(yaml_file: Path) -> Optional[dict]:
    """Parse a single YAML file and extract panel and data source info."""
    data = cm_utils.load_yaml(yaml_file)
    panel_config = data.get("Panel Config")
    if not isinstance(panel_config, dict):
        return None

    filename = (
        yaml_file.name.split("_", 1)[1] if "_" in yaml_file.name else yaml_file.name
    )

    panel_id = panel_config.get("id")
    if panel_id and panel_id >= 100:
        panel_id = panel_id // 100

    data_sources = []
    for ds in panel_config.get("data source", []):
        for key, value in ds.items():
            if isinstance(value, dict) and "id" in value and "title" in value:
                data_sources.append({
                    "type": key,
                    "id": value["id"] % 100,
                    "title": value["title"],
                })

    return {
        "file": filename,
        "panel_id": panel_id,
        "panel_title": panel_config.get("title"),
        "panel_alias": panel_config.get("alias"),
        "data_sources": data_sources,
    }


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Parse panel configuration from YAML files"
    )
    parser.add_argument("directory", help="Directory containing YAML files")
    parser.add_argument("output", nargs="?", help="Output YAML file (optional)")
    parser.add_argument(
        "--latest-arch",
        help="Specify this architecture as latest (adds metadata to output)",
    )
    args = parser.parse_args()

    directory = Path(args.directory)
    if not directory.is_dir():
        print(f"Error: '{args.directory}' is not a valid directory")
        sys.exit(1)

    results = []
    for yaml_file in sorted(directory.glob("*.yaml")):
        parsed = parse_panel_config(yaml_file)
        if parsed:
            results.append(parsed)

    if not results:
        print("No valid panel configurations found.")
        sys.exit(1)

    for panel in results:
        print(f"\n{'=' * 80}")
        print(f"File: {panel['file']}")
        print(f"Panel ID: {panel['panel_id']}")
        print(f"Panel Title: {panel['panel_title']}")
        if panel.get("panel_alias"):
            print(f"Panel Alias: {panel['panel_alias']}")
        print(f"\nData Sources ({len(panel['data_sources'])}):")
        for ds in panel["data_sources"]:
            print(f"  - {ds['type']}: {ds['id']} - {ds['title']}")

    if args.output:
        output_data: Any = results
        if args.latest_arch:
            output_data = {"latest_arch": args.latest_arch, "panels": results}
        cm_utils.save_yaml(output_data, args.output, AUTOGEN_TEXT)
        print(f"\nResults saved to: {args.output}")


if __name__ == "__main__":
    main()
