import configparser
from pathlib import Path

from pygeai import logger
from pygeai.cli.commands import Option
from pygeai.cli.texts.welcome import (
    WELCOME_BANNER,
    FEATURE_CATEGORIES,
    FEATURE_TOUR_HEADER,
    RESOURCES_FOOTER,
    COMPLETION_MESSAGE
)
from pygeai.core.common.config import SETTINGS_DIR
from pygeai.core.utils.console import Console
from pygeai.core.utils.first_run import mark_first_run_complete, reset_first_run


def validate_credentials_file(alias: str = "default") -> dict:
    """
    Validates credentials file syntax and completeness.
    
    Args:
        alias: The profile alias to validate (default: "default")
    
    Returns:
        dict: {
            'valid': bool,
            'errors': list,
            'warnings': list,
            'auth_type': str  # 'api_key', 'oauth', or 'none'
        }
    """
    result = {
        'valid': True,
        'errors': [],
        'warnings': [],
        'auth_type': 'none'
    }
    
    creds_file = SETTINGS_DIR / "credentials"
    
    if not creds_file.exists():
        result['valid'] = False
        result['errors'].append("Credentials file not found")
        return result
    
    config = configparser.ConfigParser()
    try:
        config.read(creds_file)
    except configparser.Error as e:
        result['valid'] = False
        result['errors'].append(f"Invalid INI syntax: {e}")
        return result
    
    if alias not in config:
        result['valid'] = False
        result['errors'].append(f"Alias '{alias}' not found in credentials file")
        return result
    
    section = config[alias]
    
    has_api_key = 'geai_api_key' in section and section.get('geai_api_key', '').strip()
    has_oauth = 'geai_oauth_access_token' in section and section.get('geai_oauth_access_token', '').strip()
    
    if has_api_key and has_oauth:
        result['warnings'].append(
            "Both API key and OAuth token found with values. "
            "This may cause unexpected behavior."
        )
    
    if has_api_key:
        result['auth_type'] = 'api_key'
        
        if not section['geai_api_key'].strip():
            result['errors'].append("GEAI_API_KEY is empty")
            result['valid'] = False
        
        if 'geai_api_base_url' not in section:
            result['errors'].append("GEAI_API_BASE_URL is required")
            result['valid'] = False
        elif not section['geai_api_base_url'].strip():
            result['errors'].append("GEAI_API_BASE_URL is empty")
            result['valid'] = False
    
    elif has_oauth:
        result['auth_type'] = 'oauth'
        
        if not section['geai_oauth_access_token'].strip():
            result['errors'].append("GEAI_OAUTH_ACCESS_TOKEN is empty")
            result['valid'] = False
        
        if 'geai_project_id' not in section:
            result['errors'].append("GEAI_PROJECT_ID is required for OAuth")
            result['valid'] = False
        elif not section['geai_project_id'].strip():
            result['errors'].append("GEAI_PROJECT_ID is empty")
            result['valid'] = False
        
        if 'geai_api_base_url' not in section:
            result['errors'].append("GEAI_API_BASE_URL is required")
            result['valid'] = False
        elif not section['geai_api_base_url'].strip():
            result['errors'].append("GEAI_API_BASE_URL is empty")
            result['valid'] = False
        
        if 'geai_organization_id' not in section or not section['geai_organization_id'].strip():
            result['warnings'].append("GEAI_ORGANIZATION_ID is optional but recommended")
    
    else:
        result['valid'] = False
        result['errors'].append(
            "No authentication method configured. "
            "Set either GEAI_API_KEY or GEAI_OAUTH_ACCESS_TOKEN with a valid value"
        )
    
    if 'geai_api_eval_url' not in section or not section['geai_api_eval_url'].strip():
        result['warnings'].append(
            "GEAI_API_EVAL_URL not set. Required for Evaluation module."
        )
    
    return result


def display_validation_results(validation: dict) -> None:
    """
    Display validation results with professional formatting.
    
    Args:
        validation: Dictionary with validation results
    """
    if validation['valid']:
        Console.write_success("[OK] Configuration validated successfully")
        Console.write_stdout(f"     Auth type: {validation['auth_type']}")
        
        Console.write_stdout("\nTesting connection to GEAI API...")
        try:
            from pygeai.health.clients import HealthClient
            status = HealthClient().check_api_status()
            Console.write_success(f"[OK] API Status: {status}")
        except Exception as e:
            logger.debug(f"Connection test failed: {e}")
            Console.write_warning(f"[WARNING] Connection test failed: {e}")
    else:
        Console.write_stderr("[ERROR] Configuration validation failed:")
        for error in validation['errors']:
            Console.write_stderr(f"  * {error}")
    
    if validation['warnings']:
        Console.write_stdout("")
        for warning in validation['warnings']:
            Console.write_warning(f"[WARNING] {warning}")


def run_configure_wizard() -> None:
    """
    Run the configuration wizard.
    """
    from pygeai.cli.commands.configuration import configure
    configure(option_list=[])


def check_and_setup_credentials() -> None:
    """
    Check existing credentials and offer to configure if needed.
    """
    Console.write_stdout("\n=== STEP 1: Credentials Setup ===\n")
    
    creds_file = SETTINGS_DIR / "credentials"
    
    if creds_file.exists():
        validation = validate_credentials_file("default")
        
        if validation['valid']:
            Console.write_success("[OK] Credentials file found and valid")
            Console.write_stdout(f"     Auth type: {validation['auth_type']}")
            
            if validation['warnings']:
                Console.write_stdout("")
                for warning in validation['warnings']:
                    Console.write_warning(f"[WARNING] {warning}")
            
            Console.write_stdout("\nTesting connection to GEAI API...")
            try:
                from pygeai.health.clients import HealthClient
                status = HealthClient().check_api_status()
                Console.write_success(f"[OK] Connection successful! API Status: {status}")
            except Exception as e:
                logger.debug(f"Connection test failed: {e}")
                Console.write_warning(f"[WARNING] Connection test failed: {e}")
                response = input("\nWould you like to reconfigure? [y/N]: ").strip().lower()
                if response == 'y':
                    run_configure_wizard()
                    validation = validate_credentials_file("default")
                    display_validation_results(validation)
        else:
            Console.write_stderr("[ERROR] Credentials file has errors:")
            for error in validation['errors']:
                Console.write_stderr(f"  * {error}")
            
            if validation['warnings']:
                Console.write_stdout("")
                for warning in validation['warnings']:
                    Console.write_warning(f"[WARNING] {warning}")
            
            response = input("\nWould you like to fix configuration? [Y/n]: ").strip().lower()
            if response != 'n':
                run_configure_wizard()
                validation = validate_credentials_file("default")
                display_validation_results(validation)
    else:
        Console.write_stdout("No credentials found. Let's set them up!\n")
        run_configure_wizard()
        validation = validate_credentials_file("default")
        display_validation_results(validation)


def show_feature_detail(feature_key: str) -> None:
    """
    Display detailed information about a specific feature.
    
    Args:
        feature_key: The feature category key (1-8)
    """
    if feature_key not in FEATURE_CATEGORIES:
        return
    
    feature = FEATURE_CATEGORIES[feature_key]
    
    Console.write_stdout(f"\n--- {feature['name']} ---")
    Console.write_stdout(feature['description'])
    Console.write_stdout("")
    
    if 'docs' in feature:
        Console.write_stdout(f"Documentation: {feature['docs']}")
        Console.write_stdout("")
    
    Console.write_stdout("Examples:")
    for example in feature['examples']:
        Console.write_stdout(f"  {example}")
    
    if 'commands' in feature:
        Console.write_stdout("\nRelated commands:")
        for cmd in feature['commands']:
            Console.write_stdout(f"  {cmd}")
    
    Console.write_stdout("\nPress Enter to continue...")
    input()


def feature_tour() -> None:
    """
    Interactive feature tour allowing users to explore capabilities.
    """
    Console.write_stdout("\n=== STEP 2: Feature Tour ===\n")
    Console.write_stdout(FEATURE_TOUR_HEADER)
    
    for key, feature in FEATURE_CATEGORIES.items():
        Console.write_stdout(f"[{key}] {feature['name']}")
        Console.write_stdout(f"    {feature['description']}")
        if 'commands' in feature:
            Console.write_stdout(f"    Commands: {', '.join(feature['commands'])}")
        if 'docs' in feature:
            Console.write_stdout(f"    Learn more: {feature['docs']}")
        Console.write_stdout("")
    
    while True:
        response = input("Enter a number to explore (1-9), or press Enter to skip: ").strip()
        
        if not response:
            break
        
        if response in FEATURE_CATEGORIES:
            show_feature_detail(response)
        else:
            Console.write_stdout("Invalid selection. Please enter a number between 1-9.\n")


def show_resources() -> None:
    """
    Display resources and next steps.
    """
    Console.write_stdout("\n=== STEP 3: Next Steps ===\n")
    Console.write_stdout(RESOURCES_FOOTER)


def welcome_wizard(option_list: list = None) -> None:
    """
    Main welcome wizard orchestrator.
    
    Args:
        option_list: List of tuples (option, value) for command options
    """
    options_dict = {opt.name: arg for opt, arg in option_list} if option_list else {}
    
    quick_mode = 'quick' in options_dict
    tour_only = 'tour' in options_dict
    reset = 'reset' in options_dict
    no_setup = 'no_setup' in options_dict
    
    if reset:
        reset_first_run()
        Console.write_success("First-run marker has been reset. Run 'geai' to see the welcome wizard again.")
        return
    
    Console.write_stdout(WELCOME_BANNER)
    input()
    
    if not no_setup and not tour_only:
        check_and_setup_credentials()
    
    if not quick_mode and not no_setup:
        feature_tour()
        show_resources()
    elif quick_mode:
        Console.write_stdout("\n" + COMPLETION_MESSAGE)
    
    mark_first_run_complete()


welcome_options = [
    Option(
        "quick",
        ["--quick", "-q"],
        "Quick setup mode - skip feature tour",
        False
    ),
    Option(
        "tour",
        ["--tour", "-t"],
        "Feature tour only - skip credential setup",
        False
    ),
    Option(
        "no_setup",
        ["--no-setup"],
        "Skip credential setup",
        False
    ),
    Option(
        "reset",
        ["--reset"],
        "Reset first-run flag to show welcome wizard again",
        False
    ),
]
