"""配置管理演示示例

这个脚本演示了如何使用 config.py 读取 .env 文件中的配置
"""

import os
from pathlib import Path

# 添加项目根目录到 Python 路径
import sys

sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

from agentcenter.config import get_settings


def demo_basic_usage():
    """基本用法演示"""
    print("=" * 60)
    print("基本用法演示")
    print("=" * 60)

    settings = get_settings()

    print(f"应用名称: {settings.app_name}")
    print(f"调试模式: {settings.debug}")
    print(f"日志级别: {settings.log_level}")
    print(f"API 密钥: {settings.api_key}")
    print()


def demo_field_mapping():
    """字段映射演示"""
    print("=" * 60)
    print("字段映射关系")
    print("=" * 60)

    mapping = {
        "app_name": "APP_NAME",
        "debug": "DEBUG",
        "log_level": "LOG_LEVEL",
        "api_key": "API_KEY",
    }

    settings = get_settings()

    for python_field, env_var in mapping.items():
        python_value = getattr(settings, python_field)
        env_value = os.getenv(env_var)

        print(f"Python 字段: {python_field:15} → 环境变量: {env_var:15}")
        print(f"  Python 值: {python_value}")
        print(f"  .env 值:   {env_value}")
        print()


def demo_priority():
    """优先级演示"""
    print("=" * 60)
    print("配置优先级演示")
    print("=" * 60)

    # 1. 默认值
    print("1. 默认值（在 Field 中定义）:")
    print("   app_name: 'Agent Center'")
    print()

    # 2. .env 文件值
    print("2. .env 文件值（如果存在）:")
    env_file = Path(__file__).parent.parent / ".env"
    if env_file.exists():
        print(f"   .env 文件存在于: {env_file}")
        with open(env_file) as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith("#"):
                    print(f"   {line}")
    else:
        print("   .env 文件不存在")
    print()

    # 3. 环境变量
    print("3. 系统环境变量（最高优先级）:")
    for var in ["APP_NAME", "DEBUG", "LOG_LEVEL", "API_KEY"]:
        value = os.getenv(var)
        if value:
            print(f"   {var}={value}")
    print()

    # 最终结果
    settings = get_settings()
    print("最终配置值:")
    print(f"   app_name:  {settings.app_name}")
    print(f"   debug:     {settings.debug}")
    print(f"   log_level: {settings.log_level}")
    print(f"   api_key:   {settings.api_key}")
    print()


def demo_type_conversion():
    """类型转换演示"""
    print("=" * 60)
    print("类型转换演示")
    print("=" * 60)

    settings = get_settings()

    print("字符串类型:")
    print(f"  app_name: {settings.app_name!r} (type: {type(settings.app_name).__name__})")
    print()

    print("布尔类型:")
    print(f"  debug: {settings.debug!r} (type: {type(settings.debug).__name__})")
    print("  .env 中的 'true'/'false' 自动转换为 Python 的 True/False")
    print()

    print("字符串类型:")
    print(f"  log_level: {settings.log_level!r} (type: {type(settings.log_level).__name__})")
    print()

    print("可选类型 (str | None):")
    print(f"  api_key: {settings.api_key!r} (type: {type(settings.api_key).__name__})")
    print()


def demo_all_config():
    """显示所有配置"""
    print("=" * 60)
    print("所有配置项（使用 model_dump）")
    print("=" * 60)

    settings = get_settings()
    config_dict = settings.model_dump()

    for key, value in config_dict.items():
        print(f"{key:15} = {value!r}")
    print()


def demo_env_example():
    """显示 .env 示例"""
    print("=" * 60)
    print(".env 文件示例")
    print("=" * 60)

    print("创建一个 .env 文件，内容如下：")
    print()
    print("# 应用配置")
    print("APP_NAME=My Custom Agent Center")
    print("DEBUG=true")
    print("LOG_LEVEL=DEBUG")
    print()
    print("# API 密钥")
    print("API_KEY=sk-1234567890abcdef")
    print()
    print("然后运行此脚本，配置会自动读取！")
    print()


if __name__ == "__main__":
    print("\n" + "🔧 配置管理演示程序 🔧".center(60, "="))
    print()

    # 运行所有演示
    demo_basic_usage()
    demo_field_mapping()
    demo_type_conversion()
    demo_all_config()
    demo_priority()
    demo_env_example()

    print("=" * 60)
    print("演示完成！")
    print("=" * 60)
