# detect_abnormal.py
import requests
import json
import re
from config import DEEPSEEK_API_KEY


def detect_abnormal(text):
    """
    异常行为检测核心函数
    """
    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json",
        "X-Deepseek-Version": "2024-05-15"
    }

    request_body = {
        "model": "deepseek-chat",
        "messages": [
            {
                "role": "system",
                "content": """作为安全分析专家，你只能输出严格JSON格式：
{
  "prediction": "normal|abnormal",
  "confidence": 0.0-1.0,
  "reason": "具体分析原因"
}
请按以下规则判断：
1. 涉及明火、吸烟、危险品立即判为abnormal
2. 涉及肢体冲突、奔跑、危险驾驶等剧烈动作为abnormal
3. 常规行为判为normal"""
            },
            {
                "role": "user",
                "content": f"分析场景：{text}"
            }
        ],
        "temperature": 0.1,
        "max_tokens": 300
    }

    try:
        response = requests.post(
            "https://api.deepseek.com/v1/chat/completions",
            headers=headers,
            json=request_body
        )
        response.raise_for_status()

        raw_content = response.json()['choices'][0]['message']['content']
        json_match = re.search(r'\{.*\}', raw_content, re.DOTALL)
        if not json_match:
            raise ValueError("未检测到有效JSON格式")
        result = json.loads(json_match.group())
        required_fields = ['prediction', 'confidence', 'reason']
        if not all(field in result for field in required_fields):
            raise ValueError("响应缺少必要字段")

        return {
            "prediction": result['prediction'],
            "confidence": round(float(result['confidence']), 4),
            "reason": result['reason'][:100]  # 限制原因长度
        }

    except requests.exceptions.RequestException as e:
        return {"error": f"API请求失败: {str(e)}"}
    except json.JSONDecodeError:
        return {"error": "JSON解析失败"}
    except Exception as e:
        return {"error": f"处理异常: {str(e)}"}


def manual_input_mode():
    print("=" * 40)
    print("手动检测模式已启动（输入 q 退出）")
    print("=" * 40)

    while True:
        try:
            user_input = input("\n请输入视频描述内容：")

            if user_input.lower() == 'q':
                print("\n退出检测模式")
                break

            if not user_input.strip():
                print("输入内容不能为空！")
                continue

            # 执行检测
            result = detect_abnormal(user_input)

            # 结果展示
            print("\n" + "-" * 30)
            if 'error' in result:
                print(f"错误：{result['error']}")
            else:
                status = "异常" if result['prediction'] == 'abnormal' else '正常'
                print(f"检测结果：{status}")
                print(f"置信度：{result['confidence'] * 100:.1f}%")
                print(f"原因分析：{result['reason']}")
            print("-" * 30)

        except KeyboardInterrupt:
            print("\n操作已取消")
            break


if __name__ == '__main__':
    manual_input_mode()