"""Version information loader.

Reads ``version.json`` (typically CI-generated) and exposes the data
as a ``StatusSource``-compatible object.
"""

import json
import logging
import os
from typing import Any, Dict, Optional

from brinkhaustools.common.status import StatusSource

log = logging.getLogger(__name__)

_DEFAULTS: Dict[str, Any] = {
    "Project_Name": "Unknown",
    "Version": "dev",
    "Branch": "Unknown",
    "CI_Time": "Unknown",
    "Architecture": "Unknown",
}


class VersionInformation(StatusSource):
    """Load and serve version metadata from a JSON file."""

    def __init__(self, file_path: str = "helper/version.json") -> None:
        super().__init__(refresh_time_sec=3600)
        self._data = self._load(file_path)
        log.info("Version information: %s", self._data)

    @staticmethod
    def _load(path: str) -> Dict[str, Any]:
        try:
            with open(path) as f:
                return json.load(f)
        except Exception:
            log.warning("Could not read %s, using defaults", path)
            return dict(_DEFAULTS)

    # ------------------------------------------------------------------
    # Public API
    # ------------------------------------------------------------------
    @property
    def version(self) -> str:
        return str(self._data.get("Version", "dev"))

    @property
    def data(self) -> Dict[str, Any]:
        return dict(self._data)

    def get_status(self) -> Dict[str, Any]:
        return {
            "Version": self._data.get("Version", "dev"),
            "Branch": self._data.get("Branch", "Unknown"),
            "CI-Time": self._data.get("CI_Time", "Unknown"),
        }

    def get_name(self) -> str:
        return "Version information"
