"""Max Bridge - Integration package for Maxtest test management system."""

import logging
from pathlib import Path
from typing import Optional, Dict, Any

from .config import load_config, MaxtestConfig
from .archiver import create_temp_zip_archive
from .client import MaxtestClient
from .exceptions import (
    MaxtestBridgeError,
    ConfigurationError,
    AuthenticationError,
    ArchiveError,
    UploadError,
    NetworkError,
)

__version__ = "0.1.0"
__all__ = [
    "upload_results",
    "MaxtestConfig",
    "load_config",
    "MaxtestClient",
    "MaxtestBridgeError",
    "ConfigurationError",
    "AuthenticationError",
    "ArchiveError",
    "UploadError",
    "NetworkError",
]

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='[%(levelname)s] %(name)s: %(message)s'
)
logger = logging.getLogger(__name__)


def upload_results(
    results_dir: str,
    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,
    metadata: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """
    Upload test results to Maxtest.
    
    This is the main entry point for the package. It handles:
    1. Loading configuration
    2. Archiving the results directory
    3. Uploading to Maxtest API
    4. Cleanup
    
    Args:
        results_dir: Path to the allure-results directory
        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 (e.g., staging, production)
        version: Application version being tested
        test_plan_id: Test plan ID to associate with
        fail_on_upload_error: Whether to raise exception on upload failure
        timeout: Request timeout in seconds
        metadata: Additional metadata to include in the upload
        
    Returns:
        Dict containing the API response
        
    Raises:
        ConfigurationError: If configuration is invalid
        ArchiveError: If archiving fails
        AuthenticationError: If authentication fails (401)
        UploadError: If upload fails and fail_on_upload_error is True
        NetworkError: If network fails and fail_on_upload_error is True
        
    Example:
        >>> from maxtest_bridge import upload_results
        >>> result = upload_results(
        ...     results_dir="./allure-results",
        ...     base_url="https://maxtest.example.com",
        ...     api_key="your-api-key",
        ...     launch_name="Nightly Tests"
        ... )
    """
    logger.info(f"Max Bridge v{__version__}")
    
    # Load configuration
    config = load_config(
        base_url=base_url,
        api_key=api_key,
        project_id=project_id,
        launch_name=launch_name,
        launch_description=launch_description,
        environment=environment,
        version=version,
        test_plan_id=test_plan_id,
        fail_on_upload_error=fail_on_upload_error,
        timeout=timeout,
    )
    
    # Create ZIP archive
    logger.info(f"Archiving results from: {results_dir}")
    zip_path = create_temp_zip_archive(results_dir)
    logger.info(f"Created archive: {zip_path}")
    
    try:
        # Upload to Maxtest
        with MaxtestClient(config) as client:
            result = client.upload_results(zip_path, metadata=metadata)
            return result
    finally:
        # Cleanup temporary zip file
        try:
            zip_path.unlink()
            logger.debug(f"Cleaned up temporary file: {zip_path}")
        except Exception as e:
            logger.warning(f"Failed to cleanup temporary file {zip_path}: {e}")
