"""Module for handling dependency overrides in UiPath Robot packages."""

import tomllib
from pathlib import Path
from typing import Any

import tomli_w

from uipath.robot.infra import get_logger


def load_dependency_overrides() -> dict[str, Any] | None:
    """Load dependency overrides from uipath.robot.toml."""
    config_path = Path.cwd() / "uipath.robot.toml"

    if not config_path.exists():
        return None

    try:
        with open(config_path, "rb") as f:
            config = tomllib.load(f)
        return config.get("dependencies", {})
    except Exception as e:
        get_logger().warning(f"Failed to load {config_path}: {e}")
        return None


def apply_dependency_overrides(
    process_path: Path, overrides: dict[str, Any], logger: Any
) -> bool:
    """Apply dependency overrides to a package's pyproject.toml."""
    pyproject_path = process_path / "pyproject.toml"
    logger = get_logger()
    if not pyproject_path.exists():
        logger.warning("No pyproject.toml found, skipping dependency overrides")
        return True

    try:
        with open(pyproject_path, "rb") as f:
            pyproject = tomllib.load(f)

        project_deps = pyproject.get("project", {}).get("dependencies", [])

        # Convert list format to dict for easier manipulation
        deps_dict: dict[str, str] = {}
        for dep in project_deps:
            parts = (
                dep.replace(">=", " ")
                .replace("<=", " ")
                .replace("==", " ")
                .replace("~=", " ")
                .replace("!=", " ")
                .split()
            )
            if parts:
                deps_dict[parts[0]] = dep

        overridden = []
        uv_sources: dict[str, Any] = {}

        for pkg_name, override_value in overrides.items():
            if isinstance(override_value, dict):
                path = override_value.get("path")
                editable = override_value.get("editable", True)

                if path:
                    uv_sources[pkg_name] = {
                        "path": str(Path(path).absolute()),
                        "editable": editable,
                    }
                    if pkg_name in deps_dict:
                        overridden.append(pkg_name)

            elif isinstance(override_value, str):
                dep_spec = (
                    f"{pkg_name}{override_value}"
                    if override_value.startswith((">=", "<=", "==", "~=", "!="))
                    else f"{pkg_name}{override_value}"
                )
                if pkg_name in deps_dict:
                    overridden.append(pkg_name)
                deps_dict[pkg_name] = dep_spec

        pyproject.setdefault("project", {})["dependencies"] = list(deps_dict.values())

        if uv_sources:
            pyproject.setdefault("tool", {}).setdefault("uv", {}).setdefault(
                "sources", {}
            ).update(uv_sources)

        with open(pyproject_path, "wb") as f:
            tomli_w.dump(pyproject, f)

        if overridden:
            logger.info(f"Overridden dependencies: {', '.join(overridden)}", indent=1)

        return True

    except Exception as e:
        logger.error(f"Failed to apply dependency overrides: {e}")
        return False
