#!/usr/bin/env python3
"""
Test script for Google Alerts Reporter Web Application
Validates setup and basic functionality
"""
import os
import sys
import requests
from pathlib import Path
from dotenv import load_dotenv

# Colors for terminal output
class Colors:
    GREEN = '\033[92m'
    RED = '\033[91m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    RESET = '\033[0m'
    BOLD = '\033[1m'


def log_info(message):
    print(f"{Colors.BLUE}ℹ{Colors.RESET} {message}")


def log_success(message):
    print(f"{Colors.GREEN}✓{Colors.RESET} {message}")


def log_warning(message):
    print(f"{Colors.YELLOW}⚠{Colors.RESET} {message}")


def log_error(message):
    print(f"{Colors.RED}✗{Colors.RESET} {message}")


def check_file_exists(filepath, name):
    """Check if a file exists."""
    if Path(filepath).exists():
        log_success(f"{name} exists")
        return True
    else:
        log_error(f"{name} not found at {filepath}")
        return False


def check_env_variable(var_name, required=True):
    """Check if environment variable is set."""
    value = os.getenv(var_name)

    if value and value != f"SEU_API_KEY_AQUI":
        log_success(f"{var_name} is configured")
        return True
    else:
        if required:
            log_error(f"{var_name} not configured in .env")
        else:
            log_warning(f"{var_name} not configured (optional)")
        return not required


def check_directory_exists(dirpath, name):
    """Check if directory exists."""
    if Path(dirpath).exists():
        log_success(f"{name} directory exists")
        return True
    else:
        log_warning(f"{name} directory not found (will be created)")
        return False


def check_python_packages():
    """Check if required Python packages are installed."""
    required_packages = [
        'fastapi',
        'uvicorn',
        'jinja2',
        'google.auth',
        'googleapiclient',
        'bs4',
        'requests',
        'dotenv',
        'weasyprint',
        'passlib'
    ]

    all_installed = True
    for package in required_packages:
        try:
            __import__(package)
            log_success(f"Package '{package}' installed")
        except ImportError:
            log_error(f"Package '{package}' not installed")
            all_installed = False

    return all_installed


def check_app_running(url="http://localhost:8000"):
    """Check if application is running."""
    try:
        response = requests.get(f"{url}/health", timeout=5)
        if response.status_code == 200:
            log_success(f"Application is running at {url}")
            return True
        else:
            log_error(f"Application returned status {response.status_code}")
            return False
    except requests.exceptions.ConnectionError:
        log_warning(f"Application not running at {url}")
        return False
    except Exception as e:
        log_error(f"Error checking application: {e}")
        return False


def main():
    """Run all tests."""
    print(f"""
{Colors.BOLD}{Colors.BLUE}
╔════════════════════════════════════════════════════╗
║   TEST SUITE - Google Alerts Reporter Web        ║
╚════════════════════════════════════════════════════╝
{Colors.RESET}
""")

    # Load environment variables
    if Path('.env').exists():
        load_dotenv()
        log_info("Loaded .env file")
    else:
        log_warning(".env file not found, using .env.example")
        if Path('.env.example').exists():
            load_dotenv('.env.example')

    total_checks = 0
    passed_checks = 0

    # Section 1: File Structure
    print(f"\n{Colors.BOLD}1. File Structure{Colors.RESET}")
    print("─" * 50)

    files_to_check = [
        ('app/main.py', 'FastAPI app'),
        ('app/config.py', 'Configuration'),
        ('app/auth.py', 'Authentication'),
        ('app/gmail_client.py', 'Gmail client'),
        ('app/grok_analyzer.py', 'Grok analyzer'),
        ('app/report_generator.py', 'Report generator'),
        ('templates/dashboard.html', 'Dashboard template'),
        ('static/css/style.css', 'CSS styles'),
        ('static/js/app.js', 'JavaScript app'),
        ('requirements-web.txt', 'Requirements'),
        ('Dockerfile', 'Dockerfile'),
        ('docker-compose.yml', 'Docker Compose'),
    ]

    for filepath, name in files_to_check:
        total_checks += 1
        if check_file_exists(filepath, name):
            passed_checks += 1

    # Section 2: Directories
    print(f"\n{Colors.BOLD}2. Directories{Colors.RESET}")
    print("─" * 50)

    dirs_to_check = [
        ('app', 'App'),
        ('templates', 'Templates'),
        ('static', 'Static'),
        ('reports', 'Reports'),
        ('logs', 'Logs'),
    ]

    for dirpath, name in dirs_to_check:
        total_checks += 1
        if check_directory_exists(dirpath, name):
            passed_checks += 1

    # Section 3: Environment Variables
    print(f"\n{Colors.BOLD}3. Environment Variables{Colors.RESET}")
    print("─" * 50)

    env_vars = [
        ('SECRET_KEY', True),
        ('ADMIN_USERNAME', True),
        ('ADMIN_PASSWORD', True),
        ('XAI_API_KEY', False),
        ('SEARCH_QUERY', True),
    ]

    for var_name, required in env_vars:
        total_checks += 1
        if check_env_variable(var_name, required):
            passed_checks += 1

    # Section 4: Gmail Credentials
    print(f"\n{Colors.BOLD}4. Gmail Credentials{Colors.RESET}")
    print("─" * 50)

    creds_path = os.getenv('GMAIL_CREDENTIALS_PATH', '../credentials.json')
    total_checks += 1
    if check_file_exists(creds_path, 'Gmail credentials'):
        passed_checks += 1

    # Section 5: Python Packages
    print(f"\n{Colors.BOLD}5. Python Packages{Colors.RESET}")
    print("─" * 50)

    total_checks += 1
    if check_python_packages():
        passed_checks += 1

    # Section 6: Application Status
    print(f"\n{Colors.BOLD}6. Application Status{Colors.RESET}")
    print("─" * 50)

    total_checks += 1
    if check_app_running():
        passed_checks += 1

    # Final Results
    print(f"""
{Colors.BOLD}
╔════════════════════════════════════════════════════╗
║   TEST RESULTS                                     ║
╚════════════════════════════════════════════════════╝
{Colors.RESET}

Passed: {Colors.GREEN}{passed_checks}{Colors.RESET}/{total_checks}
""")

    if passed_checks == total_checks:
        print(f"""{Colors.GREEN}{Colors.BOLD}
✓ ALL TESTS PASSED!

Ready to run:
  python3 -m uvicorn app.main:app --host 0.0.0.0 --port 8000

Or with Docker:
  docker-compose up -d
{Colors.RESET}""")
        return 0
    else:
        print(f"""{Colors.YELLOW}{Colors.BOLD}
⚠ SOME TESTS FAILED

Fix the errors above and try again.
See QUICKSTART-WEB.md for setup instructions.
{Colors.RESET}""")
        return 1


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