"""Pytest plugin for automatic result upload."""

import logging
from pathlib import Path
from typing import Optional
import pytest

from . import upload_results
from .exceptions import MaxtestBridgeError

logger = logging.getLogger(__name__)


def pytest_addoption(parser):
    """Add command-line options for max-bridge."""
    group = parser.getgroup("maxtest", "Maxtest integration")
    
    group.addoption(
        "--maxtest-upload",
        action="store_true",
        default=False,
        help="Enable automatic upload to Maxtest after test session"
    )
    
    group.addoption(
        "--maxtest-base-url",
        action="store",
        help="Maxtest API base URL"
    )
    
    group.addoption(
        "--maxtest-api-key",
        action="store",
        help="Maxtest API key"
    )
    
    group.addoption(
        "--maxtest-project-id",
        action="store",
        help="Maxtest project ID"
    )
    
    group.addoption(
        "--maxtest-launch-name",
        action="store",
        help="Test launch name"
    )
    
    group.addoption(
        "--maxtest-launch-description",
        action="store",
        help="Test launch description"
    )
    
    group.addoption(
        "--maxtest-environment",
        action="store",
        help="Test environment"
    )
    
    group.addoption(
        "--maxtest-version",
        action="store",
        help="Application version being tested"
    )
    
    group.addoption(
        "--maxtest-test-plan-id",
        action="store",
        help="Test plan ID to associate with"
    )
    
    group.addoption(
        "--maxtest-results-dir",
        action="store",
        default="allure-results",
        help="Path to allure-results directory (default: allure-results)"
    )
    
    group.addoption(
        "--maxtest-fail-on-error",
        action="store_true",
        default=False,
        help="Fail the test run if upload fails"
    )


def pytest_configure(config):
    """Configure pytest plugin."""
    config.addinivalue_line(
        "markers",
        "maxtest: mark test to be reported to Maxtest"
    )


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """
    Hook that runs after test session completes.
    
    This is where we upload the results to Maxtest.
    """
    if not config.getoption("--maxtest-upload"):
        return
    
    results_dir = config.getoption("--maxtest-results-dir")
    results_path = Path(results_dir)
    
    if not results_path.exists():
        logger.warning(
            f"Allure results directory not found: {results_dir}. "
            "Skipping Maxtest upload."
        )
        return
    
    logger.info("=" * 60)
    logger.info("Uploading results to Maxtest...")
    logger.info("=" * 60)
    
    try:
        result = upload_results(
            results_dir=results_dir,
            base_url=config.getoption("--maxtest-base-url"),
            api_key=config.getoption("--maxtest-api-key"),
            project_id=config.getoption("--maxtest-project-id"),
            launch_name=config.getoption("--maxtest-launch-name"),
            launch_description=config.getoption("--maxtest-launch-description"),
            environment=config.getoption("--maxtest-environment"),
            version=config.getoption("--maxtest-version"),
            test_plan_id=config.getoption("--maxtest-test-plan-id"),
            fail_on_upload_error=config.getoption("--maxtest-fail-on-error"),
        )
        
        if result.get("status") == "success":
            logger.info("✓ Results uploaded to Maxtest successfully")
        else:
            logger.warning("⚠ Results upload completed with warnings")
            
    except MaxtestBridgeError as e:
        logger.error(f"✗ Failed to upload results to Maxtest: {e}")
        if config.getoption("--maxtest-fail-on-error"):
            pytest.exit("Maxtest upload failed", returncode=1)
