#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
使用小红书 MCP 服务批量核实山东国保单位开放情况
"""

import json
import time
import requests
from pathlib import Path

MCP_URL = "http://localhost:18060/mcp"

# 山东各城市国保单位待核实清单
SHANDONG_GUOBAO = {
    "济南": ["洪家楼天主教堂", "千佛山", "四门塔", "灵岩寺", "府学文庙", "万竹园", "城子崖遗址"],
    "青岛": ["栈桥", "天后宫", "青岛天主教堂", "琅琊台", "康有为故居", "老舍故居"],
    "烟台": ["蓬莱水城", "烟台山近代建筑", "牟氏庄园", "长岛庙岛", "莱州云峰山刻石"],
    "威海": ["刘公岛", "成山头", "圣经山摩崖", "威海英式建筑"],
    "潍坊": ["十笏园", "沂山", "云门山", "青州古城", "诸城恐龙化石"],
    "淄博": ["齐国故城", "临淄墓群", "周村古商城", "蒲松龄故居", "博山古窑址"],
    "泰安": ["岱庙", "经石峪", "泰山石刻", "蒿里山遗址"],
    "济宁": ["孔庙", "孔府", "孔林", "颜庙", "周公庙", "孟庙", "孟府", "铁山摩崖", "武氏墓群石刻"]
}


def mcp_request(method, params=None):
    """发送 MCP 请求"""
    payload = {
        "jsonrpc": "2.0",
        "method": method,
        "params": params or {},
        "id": int(time.time() * 1000)
    }
    
    try:
        response = requests.post(MCP_URL, json=payload, timeout=30)
        return response.json()
    except Exception as e:
        return {"error": str(e)}


def initialize_mcp():
    """初始化 MCP 会话"""
    result = mcp_request("initialize", {})
    if "result" in result:
        print(f"✓ MCP 服务已连接：{result['result'].get('serverInfo', {})}")
        return True
    else:
        print(f"❌ MCP 连接失败：{result}")
        return False


def search_feeds(keyword):
    """搜索小红书内容"""
    result = mcp_request("tools/call", {
        "name": "search_feeds",
        "arguments": {"keyword": keyword}
    })
    
    if "result" in result and "content" in result["result"]:
        return result["result"]["content"]
    elif "error" in result:
        print(f"  搜索失败：{result['error']}")
        return []
    else:
        return []


def analyze_search_results(keyword, results):
    """分析搜索结果，判断开放状态"""
    if not results:
        return {
            "site": keyword,
            "status": "⏸️ 待核实",
            "confidence": "-",
            "notes_found": 0
        }
    
    open_count = 0
    close_count = 0
    recent_count = 0
    total_notes = len(results) if isinstance(results, list) else 0
    
    # 分析笔记内容
    if isinstance(results, list):
        for note in results[:10]:
            try:
                # 提取笔记文本
                text = ""
                if isinstance(note, dict):
                    text = note.get("display_title", "") + " " + note.get("desc", "")
                
                # 判断是否近期
                if any(kw in text for kw in ["2026", "2025", "今年", "最近", "刚去"]):
                    recent_count += 1
                
                # 判断开放状态
                if any(kw in text for kw in ["开放", "开门", "营业", "游玩", "打卡", "参观", "门票", "值得"]):
                    open_count += 1
                if any(kw in text for kw in ["关闭", "没开", "维修", "改造", "不开放", "别去"]):
                    close_count += 1
                    
            except Exception as e:
                pass
    
    # 判断结果
    if open_count > close_count and recent_count > 0:
        status = "✅ 开放"
        confidence = "高" if recent_count >= 3 else "中"
    elif close_count > open_count:
        status = "❌ 关闭"
        confidence = "高" if close_count >= 3 else "低"
    elif open_count > 0:
        status = "✅ 开放"
        confidence = "低"
    else:
        status = "⏸️ 待核实"
        confidence = "-"
    
    return {
        "site": keyword,
        "status": status,
        "confidence": confidence,
        "notes_found": total_notes,
        "recent": recent_count,
        "open_mentions": open_count,
        "close_mentions": close_count
    }


def verify_site(city, site):
    """核实单个景点"""
    keyword = f"{city} {site} 开放 门票"
    print(f"  搜索：{keyword}...", end=" ", flush=True)
    
    results = search_feeds(keyword)
    result = analyze_search_results(keyword, results)
    
    print(f"{result['status']} ({result['confidence']}置信度，{result['notes_found']}篇笔记)")
    
    # 间隔 2 秒，避免触发限制
    time.sleep(2)
    
    return result


def main():
    print("=" * 70)
    print("山东国保单位开放情况核实 - 小红书 MCP 服务")
    print("=" * 70)
    
    # 初始化 MCP
    if not initialize_mcp():
        print("❌ 无法连接 MCP 服务，请检查是否已启动")
        return 1
    
    # 检查登录状态
    status_result = mcp_request("tools/call", {
        "name": "check_login_status",
        "arguments": {}
    })
    print(f"登录状态检查：{status_result}")
    
    all_results = {}
    total_sites = sum(len(sites) for sites in SHANDONG_GUOBAO.values())
    verified_count = 0
    
    for city, sites in SHANDONG_GUOBAO.items():
        print(f"\n【{city}】共 {len(sites)} 处")
        city_results = []
        
        for i, site in enumerate(sites):
            print(f"  [{i+1}/{len(sites)}] ", end="")
            
            result = verify_site(city, site)
            city_results.append(result)
            verified_count += 1
        
        all_results[city] = city_results
        print(f"  ✓ {city} 完成")
    
    # 保存结果
    output_file = Path(__file__).parent / "data" / "shandong_guobao_mcp_verified.json"
    output_file.parent.mkdir(exist_ok=True)
    
    with open(output_file, "w", encoding="utf-8") as f:
        json.dump(all_results, f, ensure_ascii=False, indent=2)
    
    print(f"\n✓ 结果已保存到：{output_file}")
    
    # 统计
    print("\n" + "=" * 70)
    print("📊 核实统计")
    print("=" * 70)
    
    open_count = sum(1 for city in all_results.values() for r in city if "✅" in r['status'])
    close_count = sum(1 for city in all_results.values() for r in city if "❌" in r['status'])
    unknown_count = sum(1 for city in all_results.values() for r in city if "⏸️" in r['status'])
    
    print(f"总计核实：{verified_count} 处")
    print(f"✅ 开放：{open_count} 处 ({open_count/verified_count*100:.1f}%)")
    print(f"❌ 关闭：{close_count} 处 ({close_count/verified_count*100:.1f}%)")
    print(f"⏸️ 待核实：{unknown_count} 处 ({unknown_count/verified_count*100:.1f}%)")
    
    return 0


if __name__ == "__main__":
    exit(main())
