#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
get_unnotified_alarms.py
查询过去 1 小时内的新告警，并过滤掉已经发送过短信的告警。
"""

import json
import os
import urllib.request
from datetime import datetime, timedelta

DB_API_URL = "http://47.97.121.32:8080/VOLERTECH/app/api/oauth/getmysql"
DB_JDBC    = "snowy_cloud_mysql_copy"

LOG_DIR = "/home/admin/.openclaw/workspace-agent-200/skills/alarm-smart-handler/logs"
NOTIFIED_FILE = os.path.join(LOG_DIR, "notified_alarms.json")

def load_notified_ids() -> set:
    if not os.path.exists(NOTIFIED_FILE):
        return set()
    try:
        with open(NOTIFIED_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)
            return set(data)
    except Exception:
        return set()

def execute_sql(sql: str) -> list:
    payload = json.dumps({"basejdbc": DB_JDBC, "sql": sql}).encode("utf-8")
    req = urllib.request.Request(
        DB_API_URL,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST"
    )
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            result = json.loads(resp.read().decode("utf-8"))
            if isinstance(result, list):
                return result
            if isinstance(result, dict):
                for key in ("data", "rows", "result", "records"):
                    if key in result and isinstance(result[key], list):
                        return result[key]
            return []
    except Exception:
        return []

def main():
    # 查询过去 1 小时内的告警，按时间倒序
    sql = """
        SELECT id, battery_id, fault_code, fault_name, fault_level, actual_value, threshold_value, report_time 
        FROM tb_battery_fault_record 
        WHERE create_time >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
        ORDER BY create_time DESC
    """
    
    rows = execute_sql(sql)
    notified_ids = load_notified_ids()
    
    unnotified = []
    for row in rows:
        alarm_id = row.get("id")
        if alarm_id and alarm_id not in notified_ids:
            unnotified.append(row)
            
    if not unnotified:
        print(json.dumps({
            "status": "success",
            "count": 0,
            "message": "过去 1 小时内没有未通知的新告警。"
        }, ensure_ascii=False, indent=2))
    else:
        print(json.dumps({
            "status": "success",
            "count": len(unnotified),
            "data": unnotified,
            "message": f"发现 {len(unnotified)} 条未通知的新告警，请判断是否需要处理和发送短信。"
        }, ensure_ascii=False, indent=2))

if __name__ == "__main__":
    main()
