#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
使用小红书 MCP 核实山东国保单位开放情况（简化版）
"""

import json
import time
import os
from pathlib import Path

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


def search_xiaohongshu(keyword):
    """使用小红书 MCP 搜索"""
    import subprocess
    try:
        # 使用绝对路径调用 mcporter
        mcporter_path = '/root/.nvm/versions/node/v22.22.0/bin/mcporter'
        cmd = [mcporter_path, 'call', 'xiaohongshu.search_feeds', f'keyword: "{keyword}"']
        env = os.environ.copy()
        env['MCPORTER_CALL_TIMEOUT'] = '60000'
        # 设置 HOME 环境变量确保读取正确的配置文件
        env['HOME'] = '/root'
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=90, env=env, cwd='/root')
        # 统计 noteCard 出现次数
        count = result.stdout.count('noteCard')
        if count == 0 and result.stderr:
            print(f"[调试: stderr={result.stderr[:80]}]", end="")
        return count
    except Exception as e:
        print(f"    搜索失败：{e}")
        return 0


def verify_site(city, site):
    """核实单个景点"""
    keyword = f"{city} {site} 开放 门票"
    notes_count = search_xiaohongshu(keyword)
    
    if notes_count > 0:
        status = "✅ 开放"
        confidence = "高" if notes_count >= 5 else "中" if notes_count >= 2 else "低"
    else:
        status = "⏸️ 待核实"
        confidence = "-"
    
    return {
        "site": site,
        "status": status,
        "confidence": confidence,
        "notes_found": notes_count
    }


def main():
    print("=" * 70)
    print("山东国保单位开放情况核实 - 小红书 MCP")
    print("=" * 70)
    
    all_results = {}
    verified_count = 0
    total_notes = 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)}] {site}...", end=" ", flush=True)
            
            result = verify_site(city, site)
            city_results.append(result)
            verified_count += 1
            total_notes += result['notes_found']
            
            print(f"{result['status']} ({result['confidence']}置信度，{result['notes_found']}篇笔记)")
            
            # 间隔 2 秒，避免触发风控
            time.sleep(2)
        
        all_results[city] = city_results
        print(f"  ✓ {city} 完成")
    
    # 保存结果
    output_file = Path(__file__).parent / "data" / "shandong_guobao_mcp.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}%)")
    print(f"📱 搜索笔记：{total_notes} 篇")
    
    return 0


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