"""
临时测试：基于20260415数据进行分析
"""
import asyncio
import os
import sys
from pathlib import Path

# 代理设置
os.environ.setdefault("HTTP_PROXY", "http://127.0.0.1:29758")
os.environ.setdefault("HTTPS_PROXY", "http://127.0.0.1:29758")

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

from dotenv import load_dotenv
load_dotenv()

from agent.core.runner import AgentRunner
from agent.trace import FileSystemTraceStore
from agent.llm import create_openrouter_llm_call
from examples.auto_put_ad_mini.logging_setup import setup_logging

from examples.auto_put_ad_mini.config import (
    MAIN_CONFIG, SKILLS_DIR, TRACE_STORE_PATH, LOG_LEVEL,
)

# 导入自定义工具
from examples.auto_put_ad_mini.tools.data_query import fetch_creative_data, merge_creative_data
from examples.auto_put_ad_mini.tools.roi_calculator import calculate_roi_metrics
from examples.auto_put_ad_mini.tools.ad_decision import (
    get_ads_for_review, apply_decisions,
    query_ad_detail, modify_decisions,
)
from examples.auto_put_ad_mini.tools.report_generator import generate_report
from examples.auto_put_ad_mini.tools.guardrails import validate_decisions
from examples.auto_put_ad_mini.tools.execution_engine import execute_decisions, check_execution_feedback
from examples.auto_put_ad_mini.tools.im_approval import send_approval_request, check_approval_status


async def main():
    base_dir = Path(__file__).parent

    setup_logging(level=LOG_LEVEL)

    # 加载 system prompt
    prompt_path = base_dir / "prompts" / "system.prompt"
    system_prompt = ""
    if prompt_path.exists():
        system_prompt = prompt_path.read_text(encoding="utf-8")

    # 加载 presets
    presets_path = base_dir / "presets.json"
    if presets_path.exists():
        from agent.core.presets import load_presets_from_json
        load_presets_from_json(str(presets_path))

    store = FileSystemTraceStore(base_path=TRACE_STORE_PATH)
    runner = AgentRunner(
        trace_store=store,
        llm_call=create_openrouter_llm_call(model=MAIN_CONFIG.model),
        skills_dir=SKILLS_DIR if Path(SKILLS_DIR).exists() else None,
        logger_name="agents.auto_put_ad_mini",
    )

    config = MAIN_CONFIG
    if system_prompt:
        config.system_prompt = system_prompt

    print("=" * 70)
    print("  广告智能调控助手 — 基于20260415数据分析")
    print("=" * 70)
    print()
    print("🚀 执行：使用20260415及之前的数据进行分析")
    print()

    # 修改用户指令，明确指定使用0415数据
    messages = [{"role": "user", "content": "分析广告，使用20260415及之前的数据，不要拉取20260416的数据"}]
    config.trace_id = None

    try:
        async for item in runner.run(messages=messages, config=config):
            from agent.trace import Trace, Message
            if isinstance(item, Trace):
                if item.status == "completed":
                    print(f"\n✅ [Trace] 完成")
                elif item.status == "failed":
                    print(f"\n❌ [Trace] 失败")

            elif isinstance(item, Message):
                if item.role == "assistant" and item.content:
                    content = item.content
                    text = content.get("text", "") if isinstance(content, dict) else content
                    if text and text.strip():
                        print(f"\n💭 {text}\n")

        print("\n" + "=" * 70)
        print("✅ 执行完成")
        print("=" * 70)

    except Exception as e:
        print(f"\n❌ 执行失败: {e}")
        import traceback
        traceback.print_exc()


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