#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Heartbeat 检查脚本 - 修复版
验证展览爬取任务是否正常执行，并生成飞书同步指令
"""

import sqlite3
import json
from datetime import datetime, timedelta
from pathlib import Path

BASE_DIR = Path(__file__).parent
DATA_DIR = BASE_DIR / "data"
DB_PATH = DATA_DIR / "exhibitions.db"
NOTIFICATION_FILE = BASE_DIR.parent / "notification_pending.json"
FEISHU_SYNC_PENDING_FILE = DATA_DIR / "feishu_sync_pending.json"


def check_notification_pending():
    """检查是否有待发送的通知"""
    if not NOTIFICATION_FILE.exists():
        return None
    
    try:
        with open(NOTIFICATION_FILE, "r", encoding="utf-8") as f:
            notification = json.load(f)
        
        # 检查通知类型
        if notification.get("type") != "beijing_exhibitions":
            return None
        
        # 检查是否是今日的通知
        notify_date = notification.get("date")
        today = datetime.now().strftime("%Y-%m-%d")
        
        if notify_date != today:
            return None
        
        # 返回通知消息
        return notification.get("message")
    
    except Exception as e:
        print(f"读取通知文件失败：{e}")
        return None


def clear_notification():
    """清除已发送的通知标记"""
    if NOTIFICATION_FILE.exists():
        try:
            NOTIFICATION_FILE.unlink()
        except Exception as e:
            print(f"清除通知文件失败：{e}")


def check_crawl_status():
    """检查爬取任务状态"""
    
    # 检查数据库是否存在
    if not DB_PATH.exists():
        return {
            "status": "error",
            "message": "数据库不存在，请先运行爬虫初始化"
        }
    
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    
    # 检查今日是否有爬取记录
    today = datetime.now().strftime("%Y-%m-%d")
    
    cursor.execute("""
        SELECT COUNT(*) FROM crawl_history 
        WHERE date(crawl_time) = date('now')
    """)
    
    today_count = cursor.fetchone()[0]
    
    # 检查最近一次爬取时间
    cursor.execute("""
        SELECT source, crawl_time, status, items_count 
        FROM crawl_history 
        ORDER BY crawl_time DESC 
        LIMIT 1
    """)
    
    last_crawl = cursor.fetchone()
    
    # 检查今日新增展览数量
    cursor.execute("""
        SELECT COUNT(*) FROM exhibitions 
        WHERE date(created_at) = date('now')
    """)
    
    new_exhibitions = cursor.fetchone()[0]
    
    conn.close()
    
    # 生成状态报告
    if today_count > 0:
        status = "success"
        message = f"今日已执行 {today_count} 次爬取，新增 {new_exhibitions} 个展览"
    else:
        status = "warning"
        message = "今日尚未执行爬取任务"
    
    return {
        "status": status,
        "message": message,
        "last_crawl": {
            "source": last_crawl[0] if last_crawl else None,
            "time": last_crawl[1] if last_crawl else None,
            "status": last_crawl[2] if last_crawl else None,
            "items": last_crawl[3] if last_crawl else 0
        },
        "today_new_exhibitions": new_exhibitions
    }


def check_feishu_sync_pending():
    """检查是否有待同步的飞书文档"""
    if not FEISHU_SYNC_PENDING_FILE.exists():
        return None
    
    try:
        with open(FEISHU_SYNC_PENDING_FILE, "r", encoding="utf-8") as f:
            sync_data = json.load(f)
        
        # 检查是否是今日的同步任务
        sync_date = sync_data.get("date")
        today = datetime.now().strftime("%Y-%m-%d")
        
        if sync_date != today:
            return None
        
        return sync_data
    
    except Exception as e:
        print(f"读取飞书同步文件失败：{e}")
        return None


def clear_feishu_sync_pending():
    """清除已完成的飞书同步标记"""
    if FEISHU_SYNC_PENDING_FILE.exists():
        try:
            FEISHU_SYNC_PENDING_FILE.unlink()
        except Exception as e:
            print(f"清除飞书同步文件失败：{e}")


if __name__ == "__main__":
    result = check_crawl_status()
    
    # 检查是否有待发送的通知
    notification_msg = check_notification_pending()
    
    if notification_msg:
        # 输出通知标记（由 Travel Agent 捕获并发送）
        print(f"FEISHU_NOTIFY:{notification_msg}")
        # 清除通知标记
        clear_notification()
    
    # 检查是否有待同步的飞书文档
    feishu_sync = check_feishu_sync_pending()
    
    if feishu_sync:
        # 输出飞书同步指令（由 Travel Agent 捕获并执行）
        print(f"FEISHU_DOC_SYNC:{json.dumps(feishu_sync, ensure_ascii=False)}")
        # 清除同步标记
        clear_feishu_sync_pending()
    
    print(json.dumps(result, ensure_ascii=False, indent=2))
