#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
稷下学宫AI辩论系统 - 统一入口
Jixia Academy AI Debate System - Unified Entry Point

一个融合中国传统文化与现代AI技术的智能辩论平台
A fusion of traditional Chinese culture and modern AI technology
"""

import argparse
import asyncio
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from jixia_academy.core.debate_system.main import JixiaAcademy


def create_parser():
    """创建命令行参数解析器"""
    parser = argparse.ArgumentParser(
        description="稷下学宫AI辩论系统 - 八仙论道智能平台",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
使用示例:
  # 启动八仙论道辩论
  python -m jixia_academy baxian --topic "当前市场投资策略"
  
  # 启动记忆增强辩论
  python -m jixia_academy memory --topic "科技股投资分析"
  
  # 启动Streamlit界面
  python -m jixia_academy ui
  
  # 查看系统状态
  python -m jixia_academy status
        """
    )
    
    subparsers = parser.add_subparsers(dest='command', help='可用命令')
    
    # 八仙论道命令
    baxian_parser = subparsers.add_parser('baxian', help='启动八仙论道辩论')
    baxian_parser.add_argument('--topic', required=True, help='辩论主题')
    baxian_parser.add_argument('--rounds', type=int, default=3, help='辩论轮数')
    baxian_parser.add_argument('--participants', nargs='*', 
                             default=["铁拐李", "吕洞宾", "何仙姑", "张果老", 
                                     "蓝采和", "汉钟离", "韩湘子", "曹国舅"],
                             help='参与辩论的八仙')
    
    # 记忆增强辩论命令
    memory_parser = subparsers.add_parser('memory', help='启动记忆增强辩论')
    memory_parser.add_argument('--topic', required=True, help='辩论主题')
    memory_parser.add_argument('--engine', choices=['adk', 'swarm'], default='adk',
                             help='使用的AI引擎')
    
    # UI界面命令
    ui_parser = subparsers.add_parser('ui', help='启动用户界面')
    ui_parser.add_argument('--type', choices=['streamlit', 'web'], default='streamlit',
                          help='界面类型')
    ui_parser.add_argument('--port', type=int, default=8501, help='端口号')
    
    # 系统状态命令
    status_parser = subparsers.add_parser('status', help='查看系统状态')
    
    return parser


async def run_baxian_debate(args):
    """运行八仙论道辩论"""
    academy = JixiaAcademy()
    await academy.initialize()
    
    try:
        await academy.run_baxian_debate(
            topic=args.topic,
            rounds=args.rounds,
            participants=args.participants
        )
    finally:
        await academy.close()


async def run_memory_debate(args):
    """运行记忆增强辩论"""
    academy = JixiaAcademy()
    await academy.initialize()
    
    try:
        await academy.run_memory_enhanced_debate(
            topic=args.topic,
            engine=args.engine
        )
    finally:
        await academy.close()


def run_ui(args):
    """启动用户界面"""
    if args.type == 'streamlit':
        import subprocess
        cmd = [
            sys.executable, '-m', 'streamlit', 'run',
            'jixia_academy/ui/streamlit/streamlit_app.py',
            '--server.port', str(args.port)
        ]
        subprocess.run(cmd)
    elif args.type == 'web':
        print("Web界面开发中...")
        # TODO: 启动Web服务器


def run_status():
    """显示系统状态"""
    from jixia_academy.core.debate_system.main import check_system_status
    check_system_status()


async def main():
    """主函数"""
    parser = create_parser()
    
    if len(sys.argv) == 1:
        parser.print_help()
        return
    
    args = parser.parse_args()
    
    try:
        if args.command == 'baxian':
            await run_baxian_debate(args)
        elif args.command == 'memory':
            await run_memory_debate(args)
        elif args.command == 'ui':
            run_ui(args)
        elif args.command == 'status':
            run_status()
        else:
            parser.print_help()
    except KeyboardInterrupt:
        print("\n🛑 用户中断")
    except Exception as e:
        print(f"❌ 错误: {e}")
        import traceback
        traceback.print_exc()


if __name__ == '__main__':
    asyncio.run(main())