#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
P2-6-4 任务：核实泰安 + 济宁剩余国保单位开放情况
使用小红书 MCP 搜索（简化版，更快）
"""

import json
import time
import os
import subprocess
from pathlib import Path

# 泰安 + 济宁待核实清单（剩余 31 处）
GUOBAO_TO_VERIFY = {
    "泰安": [
        "王母池", "普照寺", "冯玉祥墓", "泰山石刻博物馆",
        "红门宫", "斗母宫", "泰山关帝庙", "玉泉寺",
        "泰山天书封禅", "泰山天街"
    ],
    "济宁": [
        "铁塔寺", "少昊陵", "尼山孔庙", "兴隆塔",
        "汶上宝相寺", "论语碑苑", "曾庙", "武氏祠",
        "梁山遗址", "南阳古镇", "邹城博物馆",
        "兖州兴隆文化园", "泗水泉林", "羊山古镇",
        "孝贤广场", "孔子研究院", "孔子博物馆",
        "济宁东大寺", "太子灵踪塔", "忠义楼",
        "微子墓"
    ]
}


def search_xiaohongshu(keyword):
    """搜索小红书笔记（简化版）"""
    try:
        cmd = ['mcporter', 'call', 'xiaohongshu.search_feeds', f'keyword: "{keyword}"']
        env = os.environ.copy()
        env['MCPORTER_CALL_TIMEOUT'] = '30000'
        env['HOME'] = '/root'
        
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=45, env=env, cwd='/root')
        count = result.stdout.count('noteCard')
        return count
    except Exception as 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("P2-6-4：山东国保核实 - 泰安 + 济宁（剩余 31 处）")
    print("=" * 70)
    
    print("\n验证小红书登录状态...")
    login_check = subprocess.run(
        ['mcporter', 'call', 'xiaohongshu.check_login_status'],
        capture_output=True, text=True, timeout=30
    )
    
    if "已登录" not in login_check.stdout:
        print("❌ 小红书未登录")
        return 1
    
    print("✅ 已登录")
    
    all_results = {}
    verified_count = 0
    total_notes = 0
    
    for city, sites in GUOBAO_TO_VERIFY.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']}篇)")
            time.sleep(0.5)  # 缩短等待时间
        
        all_results[city] = city_results
        print(f"  ✓ {city} 完成")
    
    # 保存结果
    output_file = Path('/root/.openclaw/workspace/travel/scripts/data/shandong_guobao_taian_jining_p2-6-4.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'])
    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"⏸️ 待核实：{unknown_count} 处 ({unknown_count/verified_count*100:.1f}%)")
    print(f"📱 搜索笔记：{total_notes} 篇")
    
    return 0


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