"""Configuration management for maxtest-bridge."""

import os
from pathlib import Path
from typing import Optional
from pydantic import BaseModel, Field, ValidationError, ConfigDict
from .exceptions import ConfigurationError

# Try to load dotenv if available (only if env vars not already set)
try:
    from dotenv import load_dotenv
    # Only load .env if MAXTEST_BASE_URL is not already set
    if not os.getenv("MAXTEST_BASE_URL"):
        dotenv_path = Path.cwd() / ".env"
        if dotenv_path.exists():
            load_dotenv(dotenv_path)
            print(f"[maxtest-bridge] Loaded .env from {dotenv_path}")
        else:
            print(f"[maxtest-bridge] No .env file found at {dotenv_path}")
    else:
        print(f"[maxtest-bridge] Using MAXTEST_BASE_URL from environment: {os.getenv('MAXTEST_BASE_URL')}")
except ImportError:
    # python-dotenv not installed, skip
    print("[maxtest-bridge] python-dotenv not installed, skipping .env loading")
    pass


class MaxtestConfig(BaseModel):
    """Configuration model for Maxtest bridge."""
    
    model_config = ConfigDict(validate_assignment=True)
    
    base_url: str = Field(..., description="Base URL of Maxtest API")
    api_key: str = Field(..., description="API key for authentication")
    project_id: Optional[str] = Field(None, description="Project ID")
    launch_name: Optional[str] = Field(None, description="Name of the test launch")
    launch_description: Optional[str] = Field(None, description="Description for the test launch")
    environment: Optional[str] = Field(None, description="Test environment (e.g., staging, production)")
    version: Optional[str] = Field(None, description="Application version being tested")
    test_plan_id: Optional[str] = Field(None, description="Test plan ID to associate with")
    fail_on_upload_error: bool = Field(
        default=False,
        description="Whether to fail the pipeline if upload fails"
    )
    timeout: int = Field(default=60, description="Request timeout in seconds")


def load_config(
    base_url: Optional[str] = None,
    api_key: Optional[str] = None,
    project_id: Optional[str] = None,
    launch_name: Optional[str] = None,
    launch_description: Optional[str] = None,
    environment: Optional[str] = None,
    version: Optional[str] = None,
    test_plan_id: Optional[str] = None,
    fail_on_upload_error: bool = False,
    timeout: int = 60,
) -> MaxtestConfig:
    """
    Load configuration with priority: CLI args > Environment variables > Defaults.
    
    Args:
        base_url: Maxtest API base URL
        api_key: API key for authentication
        project_id: Project identifier
        launch_name: Name of the test launch
        launch_description: Description for the test launch
        environment: Test environment
        version: Application version being tested
        test_plan_id: Test plan ID to associate with
        fail_on_upload_error: Whether to fail on upload errors
        timeout: Request timeout in seconds
        
    Returns:
        MaxtestConfig: Validated configuration object
        
    Raises:
        ConfigurationError: If required configuration is missing or invalid
    """
    # Priority: Function args > Environment variables
    config_data = {
        "base_url": base_url or os.getenv("MAXTEST_BASE_URL"),
        "api_key": api_key or os.getenv("MAXTEST_API_KEY"),
        "project_id": project_id or os.getenv("MAXTEST_PROJECT_ID"),
        "launch_name": launch_name or os.getenv("MAXTEST_LAUNCH_NAME"),
        "launch_description": launch_description or os.getenv("MAXTEST_LAUNCH_DESCRIPTION"),
        "environment": environment or os.getenv("MAXTEST_ENVIRONMENT"),
        "version": version or os.getenv("MAXTEST_VERSION"),
        "test_plan_id": test_plan_id or os.getenv("MAXTEST_TEST_PLAN_ID"),
        "fail_on_upload_error": fail_on_upload_error or os.getenv("MAXTEST_FAIL_ON_ERROR", "false").lower() == "true",
        "timeout": timeout,
    }
    
    try:
        config = MaxtestConfig(**config_data)
        return config
    except ValidationError as e:
        raise ConfigurationError(
            f"Configuration validation failed: {e}\n"
            "Please provide base_url and api_key via arguments or environment variables:\n"
            "  MAXTEST_BASE_URL - Base URL of Maxtest API\n"
            "  MAXTEST_API_KEY - API key for authentication\n"
            "  MAXTEST_PROJECT_ID - (Optional) Project ID\n"
            "  MAXTEST_LAUNCH_NAME - (Optional) Test launch name\n"
            "  MAXTEST_LAUNCH_DESCRIPTION - (Optional) Test launch description\n"
            "  MAXTEST_ENVIRONMENT - (Optional) Test environment\n"
            "  MAXTEST_VERSION - (Optional) Application version\n"
            "  MAXTEST_TEST_PLAN_ID - (Optional) Test plan ID"
        ) from e
