# Copyright (c) CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com
#

"""
UV configuration utilities for CloudZero PyPI setup.

This module provides utilities to automatically check and fix UV's global configuration
to include CloudZero's internal PyPI repository.
"""

import tomllib
from pathlib import Path

import tomli_w

# CloudZero PyPI configuration constants
CLOUDZERO_PYPI_URL = "https://pypi.cloudzero.com"
REQUIRED_EXTRA_INDEX_URLS = [CLOUDZERO_PYPI_URL]
REQUIRED_ALLOW_INSECURE_HOSTS = ["pypi.cloudzero.com"]

# UV config file path
UV_CONFIG_DIR = Path.home() / ".config" / "uv"
UV_CONFIG_FILE = UV_CONFIG_DIR / "uv.toml"


def is_uv_config_correct() -> bool:
    """
    Check if UV is configured with CloudZero's PyPI repository.

    Returns:
        bool: True if properly configured, False if needs fixing
    """
    # Check if config file exists
    if not UV_CONFIG_FILE.exists():
        return False

    # Parse the TOML config file
    try:
        with UV_CONFIG_FILE.open("rb") as f:
            config = tomllib.load(f)
    except Exception:
        return False

    # Check for extra-index-url configuration
    extra_index_urls = config.get("extra-index-url", [])
    if not isinstance(extra_index_urls, list):
        extra_index_urls = [extra_index_urls] if extra_index_urls else []

    for required_url in REQUIRED_EXTRA_INDEX_URLS:
        if required_url not in extra_index_urls:
            return False

    # Check for allow-insecure-host configuration
    allow_insecure_hosts = config.get("allow-insecure-host", [])
    if not isinstance(allow_insecure_hosts, list):
        allow_insecure_hosts = [allow_insecure_hosts] if allow_insecure_hosts else []

    return all(required_host in allow_insecure_hosts for required_host in REQUIRED_ALLOW_INSECURE_HOSTS)


def fix_uv_config() -> bool:
    """
    Create or update UV configuration with CloudZero PyPI settings.

    Returns:
        bool: True if configuration was updated successfully, False otherwise
    """
    try:
        # Create the UV config directory if it doesn't exist
        UV_CONFIG_DIR.mkdir(parents=True, exist_ok=True)

        # Prepare the configuration content
        config_content = {
            "extra-index-url": REQUIRED_EXTRA_INDEX_URLS,
            "allow-insecure-host": REQUIRED_ALLOW_INSECURE_HOSTS,
        }

        # If config file already exists, merge with existing content
        if UV_CONFIG_FILE.exists():
            try:
                with UV_CONFIG_FILE.open("rb") as f:
                    existing_config = tomllib.load(f)

                # Merge extra-index-url
                existing_urls = existing_config.get("extra-index-url", [])
                if not isinstance(existing_urls, list):
                    existing_urls = [existing_urls] if existing_urls else []

                for url in REQUIRED_EXTRA_INDEX_URLS:
                    if url not in existing_urls:
                        existing_urls.append(url)

                config_content["extra-index-url"] = existing_urls

                # Merge allow-insecure-host
                existing_hosts = existing_config.get("allow-insecure-host", [])
                if not isinstance(existing_hosts, list):
                    existing_hosts = [existing_hosts] if existing_hosts else []

                for host in REQUIRED_ALLOW_INSECURE_HOSTS:
                    if host not in existing_hosts:
                        existing_hosts.append(host)

                config_content["allow-insecure-host"] = existing_hosts

                # Merge other existing configuration
                for key, value in existing_config.items():
                    if key not in config_content:
                        config_content[key] = value

            except Exception:
                # If we can't read the existing config, we'll overwrite it
                pass

        # Write the configuration file
        with UV_CONFIG_FILE.open("wb") as f:
            tomli_w.dump(config_content, f)

        return True

    except Exception:
        # Silent failure - don't block CLI operation
        return False


def auto_fix_uv_config_if_needed() -> None:
    """
    Check UV configuration and fix it automatically if needed.

    Silently detects issues and fixes them, only printing messages when
    issues are detected and being fixed.
    """
    if not is_uv_config_correct():
        print("⚠️  UV configuration missing CloudZero PyPI repository, fixing...")
        if fix_uv_config():
            print("✅ UV configuration updated with CloudZero PyPI repository")
        # If fix fails, continue silently - don't block CLI operation
