import configparser
import os
import platform
from pathlib import Path

try:
    import tomllib  # Python 3.11+
except ModuleNotFoundError:  # pragma: no cover
    tomllib = None


TRACKER_PACKAGE_NAME = "reo-package-tracker"
DEFAULT_ENDPOINT = "https://telemetry.reo.dev/data"


class Config:
    def __init__(self):
        self.cwd = Path.cwd()
        self.project_root = self._find_project_root()
        self.pyproject = self._load_pyproject()
        self.setup_cfg = self._load_setup_cfg()
        self.reo_settings = self._read_reo_settings()

    def _find_project_root(self):
        current = self.cwd
        root = current.anchor

        while str(current) != root:
            if (current / "pyproject.toml").exists() or (current / "setup.cfg").exists():
                return current
            current = current.parent

        return self.cwd

    def _load_pyproject(self):
        pyproject_path = self.project_root / "pyproject.toml"
        if not pyproject_path.exists() or tomllib is None:
            return {}

        try:
            with pyproject_path.open("rb") as file:
                return tomllib.load(file)
        except Exception:
            return {}

    def _load_setup_cfg(self):
        setup_cfg_path = self.project_root / "setup.cfg"
        if not setup_cfg_path.exists():
            return None

        parser = configparser.ConfigParser()
        try:
            parser.read(setup_cfg_path)
            return parser
        except Exception:
            return None

    def _read_reo_settings(self):
        tool_section = self.pyproject.get("tool", {})
        settings = tool_section.get("reoSettings", {})
        return settings if isinstance(settings, dict) else {}

    def is_tracking_enabled(self):
        if os.getenv("PACKAGE_TRACKER_ANALYTICS") == "false":
            return False

        if self.reo_settings.get("defaultOptIn") is False:
            return os.getenv("PACKAGE_TRACKER_ANALYTICS") == "true"

        return True

    def is_verbose(self):
        return os.getenv("PACKAGE_TRACKER_VERBOSE") == "true"

    def get_endpoint_url(self):
        return os.getenv("PACKAGE_TRACKER_ENDPOINT") or self.reo_settings.get("endpoint") or DEFAULT_ENDPOINT

    def get_package_name(self):
        project = self.pyproject.get("project", {})
        name = project.get("name")
        if name and name != TRACKER_PACKAGE_NAME:
            return name

        if self.setup_cfg and self.setup_cfg.has_option("metadata", "name"):
            name = self.setup_cfg.get("metadata", "name")
            if name != TRACKER_PACKAGE_NAME:
                return name

        return "unknown"

    def get_package_version(self):
        project = self.pyproject.get("project", {})
        version = project.get("version")
        if version:
            return version

        if self.setup_cfg and self.setup_cfg.has_option("metadata", "version"):
            return self.setup_cfg.get("metadata", "version")

        return "unknown"

    def is_top_level_install(self):
        cwd_str = str(self.cwd)
        if "site-packages" in cwd_str or "dist-packages" in cwd_str:
            return False

        if os.getenv("PIP_REQ_TRACKER"):
            return False

        if "pip-install" in cwd_str:
            return False

        return True

    def get_config(self):
        return {
            "enabled": self.is_tracking_enabled(),
            "verbose": self.is_verbose(),
            "endpoint": self.get_endpoint_url(),
            "packageName": self.get_package_name(),
            "packageVersion": self.get_package_version(),
            "isTopLevel": self.is_top_level_install(),
            "pythonVersion": platform.python_version(),
        }
