"""
Pre-Deployment Validation Script
==================================
This script validates that all files and dependencies are ready for Windows Server deployment.
Run this BEFORE deploying to the server.
"""

import os
import sys
import importlib
from pathlib import Path

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

def print_header(text):
    print(f"\n{BOLD}{BLUE}{'='*70}{RESET}")
    print(f"{BOLD}{BLUE}{text.center(70)}{RESET}")
    print(f"{BOLD}{BLUE}{'='*70}{RESET}\n")

def print_success(text):
    print(f"{GREEN}✓{RESET} {text}")

def print_error(text):
    print(f"{RED}✗{RESET} {text}")

def print_warning(text):
    print(f"{YELLOW}⚠{RESET} {text}")

def print_info(text):
    print(f"{BLUE}ℹ{RESET} {text}")

# Validation Results
results = {
    'passed': [],
    'failed': [],
    'warnings': []
}

def validate_file_exists(filepath, description):
    """Check if a required file exists"""
    if os.path.exists(filepath):
        print_success(f"{description}: {filepath}")
        results['passed'].append(f"File exists: {filepath}")
        return True
    else:
        print_error(f"{description} MISSING: {filepath}")
        results['failed'].append(f"Missing file: {filepath}")
        return False

def validate_python_module(module_name):
    """Check if a Python module can be imported"""
    try:
        importlib.import_module(module_name)
        print_success(f"Module '{module_name}' is installed")
        results['passed'].append(f"Module installed: {module_name}")
        return True
    except ImportError as e:
        print_error(f"Module '{module_name}' is NOT installed: {e}")
        results['failed'].append(f"Missing module: {module_name}")
        return False

def check_python_version():
    """Check Python version"""
    version = sys.version_info
    version_str = f"{version.major}.{version.minor}.{version.micro}"
    
    if version.major == 3 and version.minor >= 8:
        print_success(f"Python version: {version_str} (>= 3.8 required)")
        results['passed'].append(f"Python version OK: {version_str}")
        return True
    else:
        print_error(f"Python version: {version_str} (>= 3.8 required)")
        results['failed'].append(f"Python version too old: {version_str}")
        return False

def validate_app_syntax():
    """Check if app.py has syntax errors"""
    try:
        with open('app.py', 'r', encoding='utf-8') as f:
            compile(f.read(), 'app.py', 'exec')
        print_success("app.py has no syntax errors")
        results['passed'].append("app.py syntax OK")
        return True
    except SyntaxError as e:
        print_error(f"app.py has syntax error: {e}")
        results['failed'].append(f"app.py syntax error: {e}")
        return False
    except Exception as e:
        print_error(f"Could not validate app.py: {e}")
        results['failed'].append(f"app.py validation failed: {e}")
        return False

def check_credentials():
    """Check if credentials.json exists"""
    if os.path.exists('credentials.json'):
        print_success("credentials.json found")
        results['passed'].append("credentials.json exists")
        
        # Check file size
        size = os.path.getsize('credentials.json')
        if size < 100:
            print_warning(f"credentials.json seems very small ({size} bytes). Is it valid?")
            results['warnings'].append("credentials.json file is very small")
        else:
            print_info(f"credentials.json size: {size} bytes")
        
        return True
    else:
        print_error("credentials.json NOT FOUND - Application won't work without it!")
        results['failed'].append("Missing credentials.json")
        return False

def validate_deployment_files():
    """Check all deployment files are present"""
    print_header("Checking Deployment Files")
    
    deployment_files = {
        'run_production.py': 'Production server launcher',
        'install_windows_service.ps1': 'Automated service installer',
        'web.config': 'IIS reverse proxy configuration',
        'WINDOWS_SERVER_DEPLOYMENT.md': 'Complete deployment guide',
        'DEPLOY_TO_WINDOWS_SERVER.md': 'Quick deployment guide',
        'WINDOWS_DEPLOYMENT_CHECKLIST.md': 'Deployment checklist',
        'DEPLOYMENT_FILES_README.md': 'Deployment overview',
        'requirements.txt': 'Python dependencies',
        'app.py': 'Main Flask application',
        'credentials.json': 'Google API credentials'
    }
    
    all_present = True
    for file, desc in deployment_files.items():
        if not validate_file_exists(file, desc):
            all_present = False
    
    return all_present

def validate_required_modules():
    """Check all required Python modules"""
    print_header("Checking Python Dependencies")
    
    required_modules = [
        'flask',
        'gspread',
        'flask_login',
        'google.auth',
        'google.oauth2',
        'pandas',
        'plotly',
        'xlsxwriter',
        'openpyxl',
        'waitress'
    ]
    
    all_installed = True
    for module in required_modules:
        if not validate_python_module(module):
            all_installed = False
    
    return all_installed

def validate_templates():
    """Check if template files exist"""
    print_header("Checking Template Files")
    
    templates = [
        'templates/base.html',
        'templates/index.html',
        'templates/dashboard.html',
        'templates/inventory.html',
        'templates/client_intelligence.html'
    ]
    
    all_present = True
    for template in templates:
        if not validate_file_exists(template, f"Template: {template}"):
            all_present = False
    
    return all_present

def validate_helper_modules():
    """Check if helper modules can be imported"""
    print_header("Checking Helper Modules")
    
    try:
        import client_intelligence_helper
        print_success("client_intelligence_helper.py can be imported")
        results['passed'].append("client_intelligence_helper import OK")
        return True
    except Exception as e:
        print_error(f"client_intelligence_helper.py import failed: {e}")
        results['failed'].append(f"client_intelligence_helper import failed: {e}")
        return False

def print_summary():
    """Print validation summary"""
    print_header("VALIDATION SUMMARY")
    
    total_passed = len(results['passed'])
    total_failed = len(results['failed'])
    total_warnings = len(results['warnings'])
    
    print(f"\n{GREEN}✓ Passed:{RESET} {total_passed}")
    print(f"{RED}✗ Failed:{RESET} {total_failed}")
    print(f"{YELLOW}⚠ Warnings:{RESET} {total_warnings}")
    
    if total_failed > 0:
        print(f"\n{BOLD}{RED}VALIDATION FAILED{RESET}")
        print(f"{RED}Please fix the following issues before deployment:{RESET}\n")
        for i, issue in enumerate(results['failed'], 1):
            print(f"  {i}. {issue}")
        return False
    elif total_warnings > 0:
        print(f"\n{BOLD}{YELLOW}VALIDATION PASSED WITH WARNINGS{RESET}")
        print(f"{YELLOW}Review these warnings:{RESET}\n")
        for i, warning in enumerate(results['warnings'], 1):
            print(f"  {i}. {warning}")
        print(f"\n{GREEN}You can proceed with deployment, but review warnings first.{RESET}")
        return True
    else:
        print(f"\n{BOLD}{GREEN}✓ ALL VALIDATIONS PASSED!{RESET}")
        print(f"{GREEN}Your application is ready for Windows Server deployment.{RESET}")
        return True

def main():
    print_header("PRE-DEPLOYMENT VALIDATION")
    print_info("Validating your Sales Dashboard for Windows Server deployment...")
    print_info(f"Current directory: {os.getcwd()}\n")
    
    # Run all validations
    print_header("Checking Python Environment")
    check_python_version()
    
    validate_deployment_files()
    validate_required_modules()
    validate_templates()
    validate_helper_modules()
    
    print_header("Checking Application Files")
    validate_app_syntax()
    check_credentials()
    
    # Print summary
    success = print_summary()
    
    if success:
        print(f"\n{BOLD}Next Steps:{RESET}")
        print(f"1. Create deployment ZIP: Compress-Archive -Path * -DestinationPath SalesDashboard.zip")
        print(f"2. Transfer to Windows Server")
        print(f"3. Follow: DEPLOY_TO_WINDOWS_SERVER.md")
        print(f"4. Run: install_windows_service.ps1 (as Administrator)")
        
        return 0
    else:
        print(f"\n{BOLD}Fix the issues above before deployment.{RESET}")
        return 1

if __name__ == '__main__':
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        print(f"\n\n{YELLOW}Validation interrupted by user.{RESET}")
        sys.exit(1)
    except Exception as e:
        print(f"\n{RED}Validation script error: {e}{RESET}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
