"""CLI entry point for maxtest-bridge."""

import argparse
import sys
import logging
from pathlib import Path

from . import upload_results, __version__
from .exceptions import MaxtestBridgeError

logger = logging.getLogger(__name__)


def main() -> int:
    """
    Main CLI entry point.
    
    Returns:
        int: Exit code (0 for success, 1 for failure)
    """
    parser = argparse.ArgumentParser(
        prog="maxtest-upload",
        description="Upload Allure test results to Maxtest",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Environment Variables:
  MAXTEST_BASE_URL       Base URL of Maxtest API
  MAXTEST_API_KEY        API key for authentication
  MAXTEST_PROJECT_ID     Project identifier (optional)
  MAXTEST_LAUNCH_NAME    Test launch name (optional)
  MAXTEST_ENVIRONMENT    Test environment (optional)
  MAXTEST_FAIL_ON_ERROR  Fail pipeline on upload error (default: false)

Examples:
  # Upload with explicit configuration
  maxtest-upload --results-dir ./allure-results --launch-name "Nightly Run"
  
  # Upload using environment variables
  export MAXTEST_BASE_URL=https://maxtest.example.com
  export MAXTEST_API_KEY=your-api-key
  maxtest-upload --results-dir ./allure-results
  
  # Upload with all options
  maxtest-upload \\
    --results-dir ./allure-results \\
    --base-url https://maxtest.example.com \\
    --api-key your-api-key \\
    --project-id my-project \\
    --launch-name "Regression Tests" \\
    --environment staging \\
    --fail-on-error
        """
    )
    
    parser.add_argument(
        "--version",
        action="version",
        version=f"%(prog)s {__version__}"
    )
    
    parser.add_argument(
        "--results-dir",
        type=str,
        required=True,
        help="Path to allure-results directory"
    )
    
    parser.add_argument(
        "--base-url",
        type=str,
        help="Maxtest API base URL (or set MAXTEST_BASE_URL)"
    )
    
    parser.add_argument(
        "--api-key",
        type=str,
        help="API key for authentication (or set MAXTEST_API_KEY)"
    )
    
    parser.add_argument(
        "--project-id",
        type=str,
        help="Project identifier (or set MAXTEST_PROJECT_ID)"
    )
    
    parser.add_argument(
        "--launch-name",
        type=str,
        help="Test launch name (or set MAXTEST_LAUNCH_NAME)"
    )
    
    parser.add_argument(
        "--environment",
        type=str,
        help="Test environment, e.g., staging, production (or set MAXTEST_ENVIRONMENT)"
    )
    
    parser.add_argument(
        "--fail-on-error",
        action="store_true",
        help="Fail the pipeline if upload fails (or set MAXTEST_FAIL_ON_ERROR=true)"
    )
    
    parser.add_argument(
        "--timeout",
        type=int,
        default=60,
        help="Request timeout in seconds (default: 60)"
    )
    
    parser.add_argument(
        "--verbose",
        "-v",
        action="store_true",
        help="Enable verbose logging"
    )
    
    args = parser.parse_args()
    
    # Configure logging level
    if args.verbose:
        logging.getLogger().setLevel(logging.DEBUG)
    
    # Validate results directory
    results_path = Path(args.results_dir)
    if not results_path.exists():
        logger.error(f"Results directory does not exist: {args.results_dir}")
        return 1
    
    if not results_path.is_dir():
        logger.error(f"Results path is not a directory: {args.results_dir}")
        return 1
    
    try:
        result = upload_results(
            results_dir=args.results_dir,
            base_url=args.base_url,
            api_key=args.api_key,
            project_id=args.project_id,
            launch_name=args.launch_name,
            environment=args.environment,
            fail_on_upload_error=args.fail_on_error,
            timeout=args.timeout,
        )
        
        if result.get("status") == "failed":
            logger.warning("Upload completed with warnings")
            return 0 if not args.fail_on_error else 1
        
        logger.info("✓ Upload completed successfully")
        return 0
        
    except MaxtestBridgeError as e:
        logger.error(f"Error: {e}")
        return 1
    except KeyboardInterrupt:
        logger.warning("Upload interrupted by user")
        return 130  # Standard exit code for Ctrl+C
    except Exception as e:
        logger.exception(f"Unexpected error: {e}")
        return 1


if __name__ == "__main__":
    sys.exit(main())
