"""
Configuration loading utilities.
"""
import os
import json
import sys
from argparse import Namespace
from typing import Dict, Any
from pathlib import Path

from dotenv import load_dotenv

from ..cookie.getcookie import CookieManager
from ..cookie.getcrpit import encrypt


def get_default_config() -> Dict[str, Any]:
    """
    获取默认配置，包括cookie和base_url

    Returns:
        Dict包含配置信息的字典
    """
    DEFAULT_CONFIG: Dict[str, Any] = {
        "max_workers": 20,  # 增加并发线程数以提高上传速度
        "max_retries": 3,
        "DEFAULT_CONNECT_TIMEOUT": 5,  # 增加连接超时时间，避免网络波动导致失败
        "DEFAULT_READ_TIMEOUT": 10,  # 增加读取超时时间，支持大文件上传
        "DEFAULT_RETRY_DELAY": 2,  # 减少重试延迟，快速重试
        "DEFAULT_BATCH_SIZE": 6
    }

    # 尝试从多个位置加载 .env 文件
    # 1. 当前工作目录
    # 2. 项目根目录（相对于此文件）
    # 3. 默认位置（当前工作目录）
    current_dir = Path.cwd()
    project_root = Path(__file__).parent.parent.parent
    
    env_loaded = False
    for env_path in [current_dir / '.env', project_root / '.env', Path('.env')]:
        if env_path.exists():
            load_dotenv(dotenv_path=env_path, override=True)
            env_loaded = True
            print(f"已加载环境变量文件: {env_path}", file=sys.stderr)
            break
    
    if not env_loaded:
        # 如果找不到 .env 文件，尝试从当前目录加载（默认行为）
        load_dotenv(override=True)
        print("警告: 未找到 .env 文件，尝试从环境变量读取", file=sys.stderr)
    
    # 支持大小写不敏感的环境变量读取
    name = os.getenv("name") or os.getenv("NAME")
    password = os.getenv("password") or os.getenv("PASSWORD")
    tel = os.getenv("tel") or os.getenv("TEL") or os.getenv("phoneNumber") or os.getenv("PHONENUMBER")
    base_url = os.getenv("base_url") or os.getenv("BASE_URL")



    # 加密并获取cookie
    payload = {"username": name, "password": password, "phoneNumber": tel}
    plain = json.dumps(payload, ensure_ascii=False)
    cipher = encrypt(plain)
    cookie_manager = CookieManager(base_url, cipher)
    cookie = cookie_manager.get_cookie()

    if cookie:
        DEFAULT_CONFIG["cookie"] = cookie
        DEFAULT_CONFIG["base_url"] = base_url

    return DEFAULT_CONFIG


def load_config(config_path: str = 'config.json') -> Dict:
    """
    Load configuration from environment variables or JSON file.
    Priority: Environment variables > JSON file
    
    Args:
        config_path (str): Path to the configuration file (fallback)
        
    Returns:
        dict: Configuration dictionary
    """
    # Priority 1: Try to load from environment variables
    env_config = {
        'base_url': os.getenv('BASE_URL'),
        'cookie': os.getenv('COOKIE'),
        'max_workers': os.getenv('MAX_WORKERS', '4'),
        'max_retries': os.getenv('MAX_RETRIES', '3'),
        'DEFAULT_CONNECT_TIMEOUT': os.getenv('DEFAULT_CONNECT_TIMEOUT', '10'),
        'DEFAULT_READ_TIMEOUT': os.getenv('DEFAULT_READ_TIMEOUT', '300'),
        'DEFAULT_RETRY_DELAY': os.getenv('DEFAULT_RETRY_DELAY', '2'),
        'DEFAULT_BATCH_SIZE': os.getenv('DEFAULT_BATCH_SIZE', '10')
    }
    
    # If required environment variables are set, use env config
    # base_url and orthanc_base_url are both required
    if env_config['base_url'] and env_config['orthanc_base_url'] and env_config['cookie']:
        # Convert string numbers to integers
        for key in ['max_workers', 'max_retries', 'DEFAULT_CONNECT_TIMEOUT', 
                    'DEFAULT_READ_TIMEOUT', 'DEFAULT_RETRY_DELAY', 'DEFAULT_BATCH_SIZE']:
            env_config[key] = int(env_config[key])
        return env_config
    else:
        print("未找到环境变量，将使用配置文件")
   

def create_upload_config(config: Dict) -> Namespace:
    """
    Create upload configuration namespace from config dictionary.
    
    Args:
        config (dict): Configuration dictionary
        
    Returns:
        Namespace: Upload configuration namespace
    """
    return Namespace(
        base_url=config['base_url'],
        cookie=config['cookie'],
        max_workers=config['max_workers'],
        max_retries=config['max_retries'],
        DEFAULT_CONNECT_TIMEOUT=config['DEFAULT_CONNECT_TIMEOUT'],
        DEFAULT_READ_TIMEOUT=config['DEFAULT_READ_TIMEOUT'],
        DEFAULT_RETRY_DELAY=config['DEFAULT_RETRY_DELAY'],
        DEFAULT_BATCH_SIZE=config['DEFAULT_BATCH_SIZE']
    )
