#!/usr/bin/env python3
"""
环境配置验证脚本
验证开发和生产环境的配置是否正确
"""

import os
import sys
import json
from pathlib import Path
from urllib.parse import urlparse

def validate_frontend_config(env_file):
    """验证前端环境配置"""
    print(f"\n🌐 验证前端配置: {env_file}")
    
    if not os.path.exists(env_file):
        print(f"❌ 配置文件不存在: {env_file}")
        return False
    
    config = {}
    with open(env_file, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith('#') and '=' in line:
                key, value = line.split('=', 1)
                config[key] = value
    
    # 必需配置检查
    required_configs = [
        'VITE_APP_TITLE',
        'VITE_APP_ENV',
        'VITE_API_BASE_URL',
        'VITE_WS_BASE_URL'
    ]
    
    for key in required_configs:
        if key not in config:
            print(f"❌ 缺少必需配置: {key}")
            return False
        else:
            print(f"✅ {key} = {config[key]}")
    
    # 环境特定验证
    env_type = config.get('VITE_APP_ENV', '')
    if env_type == 'development':
        # 开发环境验证
        if 'localhost' not in config.get('VITE_API_BASE_URL', ''):
            print("⚠️  开发环境建议使用localhost")
        if config.get('VITE_ENABLE_DEVTOOLS') != 'true':
            print("⚠️  开发环境建议启用开发工具")
    elif env_type == 'production':
        # 生产环境验证
        api_url = config.get('VITE_API_BASE_URL', '')
        if 'localhost' in api_url or '127.0.0.1' in api_url:
            print("❌ 生产环境不应使用localhost")
            return False
        if config.get('VITE_ENABLE_DEVTOOLS') == 'true':
            print("⚠️  生产环境建议禁用开发工具")
    
    print("✅ 前端配置验证通过")
    return True

def validate_backend_config(env_file):
    """验证后端环境配置"""
    print(f"\n🚀 验证后端配置: {env_file}")
    
    if not os.path.exists(env_file):
        print(f"❌ 配置文件不存在: {env_file}")
        return False
    
    config = {}
    with open(env_file, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith('#') and '=' in line:
                key, value = line.split('=', 1)
                config[key] = value
    
    # 必需配置检查
    required_configs = [
        'ENV',
        'SECRET_KEY',
        'DATABASE_URL',
        'REDIS_URL'
    ]
    
    for key in required_configs:
        if key not in config:
            print(f"❌ 缺少必需配置: {key}")
            return False
        else:
            # 敏感信息脱敏显示
            if 'PASSWORD' in key or 'SECRET' in key or 'TOKEN' in key or 'KEY' in key:
                value = config[key]
                if len(value) > 8:
                    masked_value = value[:4] + '*' * (len(value) - 8) + value[-4:]
                else:
                    masked_value = '*' * len(value)
                print(f"✅ {key} = {masked_value}")
            else:
                print(f"✅ {key} = {config[key]}")
    
    # 安全性检查
    secret_key = config.get('SECRET_KEY', '')
    if secret_key in ['your-secret-key', 'your-secret-key-here', 'secret']:
        print("❌ 请设置安全的密钥，不要使用默认值")
        return False
    
    if len(secret_key) < 32:
        print("⚠️  建议使用至少32位的密钥")
    
    # 数据库URL检查
    db_url = config.get('DATABASE_URL', '')
    if db_url:
        try:
            parsed = urlparse(db_url)
            print(f"📊 数据库信息: {parsed.scheme}://{parsed.hostname}:{parsed.port}/{parsed.path.lstrip('/')}")
        except Exception as e:
            print(f"⚠️  数据库URL格式可能有误: {e}")
    
    # 环境特定验证
    env_type = config.get('ENV', '')
    if env_type == 'development':
        if config.get('DEBUG') != 'true':
            print("⚠️  开发环境建议启用调试模式")
    elif env_type == 'production':
        if config.get('DEBUG') == 'true':
            print("❌ 生产环境不应启用调试模式")
            return False
        
        # 生产环境数据库检查
        if 'localhost' in db_url or '127.0.0.1' in db_url:
            print("⚠️  生产环境建议使用容器内数据库")
    
    print("✅ 后端配置验证通过")
    return True

def validate_docker_config():
    """验证Docker配置"""
    print(f"\n🐳 验证Docker配置")
    
    compose_files = [
        'docker-compose.dev.yml',
        'docker-compose.yml'
    ]
    
    for compose_file in compose_files:
        if os.path.exists(compose_file):
            print(f"✅ {compose_file} 存在")
        else:
            print(f"❌ {compose_file} 不存在")
    
    return True

def main():
    """主函数"""
    print("=== 考培练系统环境配置验证 ===")
    
    # 检查工作目录
    if not os.path.exists('kaopeilian-frontend') or not os.path.exists('kaopeilian-backend'):
        print("❌ 请在项目根目录运行此脚本")
        sys.exit(1)
    
    all_valid = True
    
    # 验证前端配置
    frontend_configs = [
        'kaopeilian-frontend/.env.development',
        'kaopeilian-frontend/.env.production'
    ]
    
    for config_file in frontend_configs:
        if os.path.exists(config_file):
            if not validate_frontend_config(config_file):
                all_valid = False
        else:
            print(f"⚠️  前端配置文件不存在: {config_file}")
    
    # 验证后端配置
    backend_configs = [
        'kaopeilian-backend/.env.development',
        'kaopeilian-backend/.env.production'
    ]
    
    for config_file in backend_configs:
        if os.path.exists(config_file):
            if not validate_backend_config(config_file):
                all_valid = False
        else:
            print(f"⚠️  后端配置文件不存在: {config_file}")
    
    # 验证Docker配置
    validate_docker_config()
    
    print(f"\n=== 验证结果 ===")
    if all_valid:
        print("✅ 所有配置验证通过")
        sys.exit(0)
    else:
        print("❌ 配置验证失败，请检查上述错误")
        sys.exit(1)

if __name__ == "__main__":
    main()
