"""Version and runtime information utilities for internetfilm-manager."""

import os
import re
from importlib import metadata as importlib_metadata


def _get_pyproject_path():
    """Return the project root pyproject.toml path if present.

    Resolves the path by walking up from the module file location:
    ``src/integrator/version.py`` → ``src/integrator`` → ``src`` → project root.
    """
    module_dir = os.path.dirname(os.path.abspath(__file__))   # src/integrator
    src_dir = os.path.dirname(module_dir)                      # src
    project_root = os.path.dirname(src_dir)                    # project root
    return os.path.join(project_root, "pyproject.toml")


def _read_version_from_pyproject(pyproject_path):
    """Read project version from a pyproject.toml file."""
    import tomllib

    try:
        with open(pyproject_path, "rb") as f:
            data = tomllib.load(f)
        return data.get("project", {}).get("version")
    except Exception:
        return None


def _read_pyproject_data(pyproject_path):
    """Read and return parsed pyproject data."""
    import tomllib

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


def _normalize_distribution_name(requirement):
    """Extract the distribution name from a dependency specifier string."""
    requirement = (requirement or "").split(";", 1)[0].strip()
    requirement = requirement.split("[", 1)[0].strip()
    match = re.match(r"^[A-Za-z0-9_.-]+", requirement)
    return match.group(0) if match else requirement


def _get_installed_distribution_version(distribution_name):
    """Return installed version for a distribution name, or None if unavailable."""
    if not distribution_name:
        return None
    try:
        return importlib_metadata.version(distribution_name)
    except importlib_metadata.PackageNotFoundError:
        return None
    except Exception:
        return None


def _collect_dependency_versions():
    """Collect dependency versions from the current project's pyproject.toml."""
    pyproject_path = _get_pyproject_path()
    data = _read_pyproject_data(pyproject_path)
    dependencies = data.get("project", {}).get("dependencies", [])

    collected = []
    for dependency in dependencies:
        dist_name = _normalize_distribution_name(dependency)
        installed_version = _get_installed_distribution_version(dist_name)
        collected.append({
            "requirement": dependency,
            "distribution": dist_name,
            "version": installed_version,
        })
    return collected


def _build_startup_banner_lines():
    """Build the compact dependency summary for the interactive startup banner."""
    dependencies = _collect_dependency_versions()
    dep_summary = ", ".join(
        f"{item['distribution']}={item['version'] or 'n/a'}"
        for item in dependencies
    )
    return [
        f"🔧 Abhängigkeiten: {dep_summary}",
    ]


def get_version():
    """Read the version preferring the local repo, otherwise from package metadata."""
    source_pyproject = _get_pyproject_path()
    if os.path.isfile(source_pyproject):
        source_version = _read_version_from_pyproject(source_pyproject)
        if source_version:
            return source_version

    for dist_name in ("kurmann-internetfilm-manager", "internetfilm-manager"):
        installed_version = _get_installed_distribution_version(dist_name)
        if installed_version:
            return installed_version

    return "unknown"
