"""Dashboard config.json registry: load and resolve project definitions."""

import json
import sys
from pathlib import Path
from typing import List, Optional

from common import AUTOBUILDER_DIR

CONFIG_SEARCH_PATHS = [
    AUTOBUILDER_DIR / "config.json",
]


def _find_config_file() -> Optional[Path]:
    for p in CONFIG_SEARCH_PATHS:
        if p.exists():
            return p
    return None


def load_projects_config(config_path: Optional[Path] = None) -> List[dict]:
    """Load the ``projects`` array from a config.json file."""
    if config_path is None:
        config_path = _find_config_file()
    if config_path is None or not config_path.exists():
        return []
    try:
        data = json.loads(config_path.read_text(encoding="utf-8"))
        return data.get("projects", [])
    except Exception:
        return []


def resolve_project_from_config(
    project_name: str, config_path: Optional[Path] = None,
) -> dict:
    """Look up a project by name in config.json and return resolved paths.

    Returns dict with keys: ``project_dir``, ``project_id``,
    ``root_initiative``, ``port``.  Raises ``SystemExit`` if not found.
    """
    projects = load_projects_config(config_path)
    for proj in projects:
        if proj.get("name") == project_name:
            autobuilder_dir = proj.get("autobuilderDir", "")
            if autobuilder_dir:
                project_dir = str(Path(autobuilder_dir).parent)
            else:
                project_dir = proj.get("dir", ".")
            return {
                "project_dir": project_dir,
                "project_id": proj["name"],
                "root_initiative": proj["name"],
                "port": proj.get("port"),
            }
    available = [p.get("name") for p in projects]
    print(f"ERROR: Project '{project_name}' not found in config.", file=sys.stderr)
    print(f"Available projects: {available}", file=sys.stderr)
    raise SystemExit(2)
