from __future__ import annotations

import os
import sys
from pathlib import Path
from typing import Optional

import importlib.metadata

try:
    import tomllib
except ModuleNotFoundError:  # pragma: no cover
    import tomli as tomllib  # type: ignore[no-redef]


def _candidate_paths() -> list[Path]:
    paths = []
    bundle_dir: Optional[str] = getattr(sys, "_MEIPASS", None)
    if bundle_dir:
        paths.append(Path(bundle_dir) / "pyproject.toml")
    paths.append(Path(__file__).resolve().parent.parent / "pyproject.toml")
    paths.append(Path(__file__).resolve().parent / "pyproject.toml")
    paths.append(Path.cwd() / "pyproject.toml")
    return paths


def _read_from_pyproject() -> Optional[str]:
    for path in _candidate_paths():
        if not path.exists():
            continue
        try:
            with path.open("rb") as handle:
                data = tomllib.load(handle)
        except (OSError, tomllib.TOMLDecodeError):
            continue
        project = data.get("project")
        if isinstance(project, dict):
            version = project.get("version")
            if isinstance(version, str):
                return version
        tool = data.get("tool")
        if isinstance(tool, dict):
            argus_cfg = tool.get("argus")
            if isinstance(argus_cfg, dict):
                version = argus_cfg.get("version")
                if isinstance(version, str):
                    return version
    return None


def _detect_version() -> str:
    try:
        return importlib.metadata.version("argus-agent")
    except importlib.metadata.PackageNotFoundError:
        pass
    override = os.environ.get("AGENT_VERSION_OVERRIDE")
    if override:
        return override
    fallback = _read_from_pyproject()
    if fallback:
        return fallback
    return "0.0.0"


VERSION: str = _detect_version()


def get_version() -> str:
    return VERSION
