"""用 dispatcher.run_single_app 等效 API 路径跑 this_month/all，验证百炼侧新 system prompt 的输出效果。"""
from __future__ import annotations

import asyncio
import json
import os
import sys
import time

sys.path.insert(0, 'apps/backend')
from dotenv import load_dotenv
load_dotenv(dotenv_path=os.path.join(os.getcwd(), '.env'))

from app.ai.budget_tracker import BudgetTracker
from app.ai.cache_service import AICacheService
from app.ai.circuit_breaker import CircuitBreaker
from app.ai.config import AIConfig
from app.ai.conversation_service import ConversationService
from app.ai.dashscope_client import DashScopeClient
from app.ai.dispatcher import AIDispatcher
from app.ai.rate_limiter import RateLimiter
from app.ai.run_log_service import AIRunLogService
from app.database import get_connection


async def main() -> None:
    cfg = AIConfig.from_env()
    run_log = AIRunLogService(get_conn=get_connection)
    dispatcher = AIDispatcher(
        client=DashScopeClient(api_key=cfg.api_key, workspace_id=cfg.workspace_id),
        cache_svc=AICacheService(),
        conv_svc=ConversationService(),
        circuit_breaker=CircuitBreaker(),
        rate_limiter=RateLimiter(),
        budget_tracker=BudgetTracker(usage_provider=run_log),
        run_log_svc=run_log,
        config=cfg,
    )

    t0 = time.monotonic()
    result = await dispatcher.run_single_app(
        app_type='app2_finance',
        context={
            'site_id': 2790685415443269,
            'time_dimension': 'this_month',
            'area': 'all',
        },
        triggered_by='admin_test_new_system_prompt',
    )
    dt = time.monotonic() - t0
    if result is None:
        print(f'FAILED after {dt:.1f}s')
        return

    insights = result.get('insights') or []
    print(f'done in {dt:.1f}s, insights={len(insights)} 条\n')
    for ins in insights:
        seq = ins.get('seq')
        title = ins.get('title')
        content = (ins.get('content') or '')
        print(f'[{seq}] {title}')
        print(f'    {content}\n')


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