import requests
import json
import re
from config import DEEPSEEK_API_KEY


def detect_gas_station_abnormal(text):
    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json"
    }

    request_body = {
        "model": "deepseek-chat",  # 使用基础通用模型
        "messages": [
            {
                "role": "system",
                "content": """作为加油站安全分析专家，你只能输出JSON格式：
{
  "prediction": "normal/safety_violation/equipment_abuse/dangerous_item/vehicle_risk",
  "confidence": 0.0-1.0,
  "reason": "分析原因"
}
请严格按以下规则判断：
1. 吸烟/明火立即判为dangerous_item
2. 使用手机判为safety_violation
3. 车辆未熄火判为vehicle_risk"""
            },
            {
                "role": "user",
                "content": f"分析场景：{text}"
            }
        ],
        "temperature": 0.01,
        "max_tokens": 200
    }

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

        # 提取原始响应文本
        raw_output = response.json()['choices'][0]['message']['content']

        # 使用正则表达式提取JSON内容
        json_str = re.search(r'\{.*\}', raw_output, re.DOTALL).group()
        result = json.loads(json_str)

        return result

    except Exception as e:
        return {"error": str(e), "raw": raw_output}


# 测试案例
if __name__ == '__main__':
    test_cases = [
        "驾驶员在加油机旁点燃香烟",
        "车辆加油时发动机持续运转",
        "乘客在加油区使用手机通话",
        "工作人员正常操作加油枪"
    ]

    for case in test_cases:
        print(f"测试场景：{case}")
        result = detect_gas_station_abnormal(case)
        print(json.dumps(result, indent=2, ensure_ascii=False))
        print("-" * 50)