"""Mode detection — developer (source) vs operator (installed)."""

from __future__ import annotations

import json
from dataclasses import dataclass


@dataclass
class EnvironmentMode:
    mode: str  # "developer" or "operator"
    axiom_version: str
    axiom_source: str  # path to source or "pypi"
    axiom_editable: bool
    neutronos_version: str
    neutronos_source: str
    neutronos_editable: bool

    def to_dict(self) -> dict:
        return {
            "mode": self.mode,
            "axiom": {
                "version": self.axiom_version,
                "source": self.axiom_source,
                "editable": self.axiom_editable,
            },
            "neutronos": {
                "version": self.neutronos_version,
                "source": self.neutronos_source,
                "editable": self.neutronos_editable,
            },
        }


def detect_mode() -> EnvironmentMode:
    """Detect whether we're running from source (developer) or installed (operator)."""
    axiom_info = _check_package("axi-platform", "axiom")
    nos_info = _check_package("neutron-os", "neutron_os")

    mode = "developer" if axiom_info["editable"] or nos_info["editable"] else "operator"

    return EnvironmentMode(
        mode=mode,
        axiom_version=axiom_info["version"],
        axiom_source=axiom_info["source"],
        axiom_editable=axiom_info["editable"],
        neutronos_version=nos_info["version"],
        neutronos_source=nos_info["source"],
        neutronos_editable=nos_info["editable"],
    )


def _check_package(dist_name: str, import_name: str) -> dict:
    """Check a package's install mode and version."""
    info: dict = {"version": "", "source": "not installed", "editable": False}

    try:
        from importlib.metadata import distribution

        dist = distribution(dist_name)
        info["version"] = dist.version

        # Check for editable install
        direct_url = dist.read_text("direct_url.json")
        if direct_url:
            url_data = json.loads(direct_url)
            if url_data.get("dir_info", {}).get("editable", False):
                info["editable"] = True
                info["source"] = url_data.get("url", "").replace("file://", "")
                return info

        info["source"] = "pypi"
    except Exception:
        pass

    return info
