#!/usr/bin/env python3
"""
Continuous Proxy Monitoring Tool - 监控本地代理的健康状态
每天自动检查，记录趋势
"""

import os
import sys
sys.path.append(os.getcwd())

import time
import json
from datetime import datetime
from openai import OpenAI
from slack_bot.llm.gemini import get_system_instruction
from slack_bot.tools.groups import get_tool_preset

MONITOR_FILE = "data/proxy_health_history.jsonl"

def check_proxy_health():
    """检查本地代理健康状态"""
    client = OpenAI(
        api_key="sk-457cbcd2e0a4467e90db1af0ae65748e",
        base_url="http://127.0.0.1:8045/v1"
    )

    system_prompt = get_system_instruction()
    tools, _ = get_tool_preset("light")

    tests_passed = 0
    tests_total = 3

    # Test 1: 简单对话
    try:
        r1 = client.chat.completions.create(
            model="gemini-3-pro-high",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": "Hello"}
            ]
        )
        test1 = bool(r1.choices[0].message.content)
        tests_passed += 1 if test1 else 0
    except:
        test1 = False

    # Test 2: 健康查询（无工具）
    try:
        r2 = client.chat.completions.create(
            model="gemini-3-pro-high",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": "Hello"}
            ]
        )
        test2 = bool(r2.choices[0].message.content)
        tests_passed += 1 if test2 else 0
    except:
        test2 = False

    # Test 3: Function calling
    try:
        r3 = client.chat.completions.create(
            model="gemini-3-pro-high",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": "今天睡得怎么样？"}
            ],
            tools=tools
        )
        test3 = bool(r3.choices[0].message.tool_calls)
        tests_passed += 1 if test3 else 0
    except:
        test3 = False

    success_rate = (tests_passed / tests_total) * 100

    # 评级
    if success_rate >= 66:
        grade = "A"
        status = "健康"
    elif success_rate >= 33:
        grade = "C"
        status = "一般"
    else:
        grade = "F"
        status = "故障"

    return {
        "timestamp": datetime.now().isoformat(),
        "success_rate": success_rate,
        "tests_passed": tests_passed,
        "tests_total": tests_total,
        "test1_basic": test1,
        "test2_health_prompt": test2,
        "test3_function_calling": test3,
        "grade": grade,
        "status": status
    }

def save_result(result):
    """保存检查结果到历史文件"""
    os.makedirs(os.path.dirname(MONITOR_FILE), exist_ok=True)

    with open(MONITOR_FILE, "a") as f:
        f.write(json.dumps(result, ensure_ascii=False) + "\n")

def load_history():
    """加载历史记录"""
    if not os.path.exists(MONITOR_FILE):
        return []

    history = []
    with open(MONITOR_FILE, "r") as f:
        for line in f:
            if line.strip():
                history.append(json.loads(line))
    return history

def print_report(result, history):
    """打印报告"""
    print("=" * 80)
    print(f"本地代理健康检查报告 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 80)

    print(f"\n当前状态: {result['grade']} ({result['status']})")
    print(f"成功率: {result['success_rate']:.1f}% ({result['tests_passed']}/{result['tests_total']})")

    print(f"\n详细测试:")
    print(f"  1. 基础对话: {'✅' if result['test1_basic'] else '❌'}")
    print(f"  2. 健康 Prompt: {'✅' if result['test2_health_prompt'] else '❌'}")
    print(f"  3. Function Calling: {'✅' if result['test3_function_calling'] else '❌'}")

    if history:
        print(f"\n历史趋势 (最近 7 次):")
        recent = history[-7:]
        for h in recent:
            date = h['timestamp'][:10]
            grade = h['grade']
            rate = h['success_rate']
            print(f"  {date}: {grade} ({rate:.0f}%)")

        # 分析趋势
        if len(recent) >= 3:
            recent_rates = [h['success_rate'] for h in recent[-3:]]
            avg_recent = sum(recent_rates) / len(recent_rates)

            if avg_recent > 60:
                trend = "✅ 恢复中"
            elif avg_recent < 30:
                trend = "❌ 持续故障"
            else:
                trend = "⚠️  不稳定"

            print(f"\n  趋势: {trend} (近期平均 {avg_recent:.1f}%)")

    print(f"\n{'-' * 80}")

    if result['test3_function_calling']:
        print("✅ 本地代理 Function Calling 已恢复！")
        print("   可以考虑继续使用本地代理")
    else:
        print("❌ 本地代理 Function Calling 仍然损坏")
        print("   建议:")
        print("   1. 继续使用 SAFETY OVERRIDE")
        print("   2. 或切换到 OpenRouter")
        print(f"   3. 定期检查（再运行此脚本）")

    print(f"\n{'=' * 80}")

def main():
    print("正在检查本地代理健康状态...\n")

    result = check_proxy_health()
    save_result(result)
    history = load_history()

    print_report(result, history)

    # 返回退出码（用于自动化）
    if result['success_rate'] >= 66:
        sys.exit(0)  # 健康
    else:
        sys.exit(1)  # 不健康

if __name__ == "__main__":
    main()
