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

import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional

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


@dataclass
class MaxtestConfig:
    """Configuration model for Maxtest bridge."""
    
    base_url: str = field(metadata={"description": "Base URL of Maxtest API"})
    api_key: str = field(metadata={"description": "API key for authentication"})
    project_id: Optional[str] = field(default=None, metadata={"description": "Project ID"})
    launch_name: Optional[str] = field(default=None, metadata={"description": "Name of the test launch"})
    launch_description: Optional[str] = field(default=None, metadata={"description": "Description for the test launch"})
    environment: Optional[str] = field(default=None, metadata={"description": "Test environment (e.g., staging, production)"})
    version: Optional[str] = field(default=None, metadata={"description": "Application version being tested"})
    test_plan_id: Optional[str] = field(default=None, metadata={"description": "Test plan ID to associate with"})
    fail_on_upload_error: bool = field(default=False, metadata={"description": "Whether to fail the pipeline if upload fails"})
    timeout: int = field(default=60, metadata={"description": "Request timeout in seconds"})
    
    def __post_init__(self):
        """Validate configuration after initialization."""
        errors = []
        
        if not self.base_url:
            errors.append("base_url: field required")
        if not self.api_key:
            errors.append("api_key: field required")
        if self.timeout < 1:
            errors.append("timeout: must be positive")
            
        if errors:
            raise ConfigurationError(
                f"Configuration validation failed: {'; '.join(errors)}\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"
            )


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,
    }
    
    return MaxtestConfig(**config_data)
