#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
P2-6-1 任务：核实济南 + 青岛剩余国保单位开放情况
使用小红书 MCP 搜索
"""

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

# 济南 + 青岛待核实清单（剩余 36 处：济南 23 + 青岛 13）
# 基于 task.md P2-6-1 任务定义
GUOBAO_TO_VERIFY = {
    "济南": [
        # 已核实 7 处后的剩余景点（共 30 处，已核实 7 处，待核实 23 处）
        "趵突泉", "大明湖", "山东博物馆", "广智院", "千佛崖造像",
        "西河遗址", "小荆山遗址", "无影山遗址", "济南老城区古建筑群",
        "济南战役纪念馆", "济南纬六路老洋行", "平阴玫瑰圣母堂",
        "长清莲花洞石窟", "章丘洛庄汉墓", "济阳闻韶台遗址",
        "商河鼓子秧歌博物馆", "平阴洪范池书院", "长清五峰山道观",
        "章丘城子崖博物馆", "济南清真南大寺", "济南府学文庙石刻",
        "济南古城墙遗址", "历城仲宫石窟"
    ],
    "青岛": [
        # 已核实 6 处后的剩余景点（共 19 处，已核实 6 处，待核实 13 处）
        "崂山", "青岛德国建筑群", "八大关", "青岛德国总督府旧址",
        "青岛啤酒博物馆", "小鱼山", "信号山", "青岛海底世界",
        "五四广场", "奥帆中心", "青岛美术馆", "青岛民俗博物馆",
        "青岛天主教堂修道院"
    ]
}


def search_xiaohongshu(keyword):
    """搜索小红书笔记"""
    try:
        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'
        env['HOME'] = '/root'
        
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=90, env=env, cwd='/root')
        
        # 统计 noteCard 数量
        count = result.stdout.count('noteCard')
        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("P2-6-1：山东国保核实 - 济南 + 青岛（剩余 36 处）")
    print("=" * 70)
    
    # 先验证登录状态
    print("\n验证小红书登录状态...")
    login_check = subprocess.run(
        ['mcporter', 'call', 'xiaohongshu.check_login_status'],
        capture_output=True, text=True, timeout=30,
        env={**os.environ, 'MCPORTER_CALL_TIMEOUT': '30000', 'HOME': '/root'}
    )
    
    if "已登录" not in login_check.stdout:
        print("❌ 小红书未登录，请先扫码登录")
        print(f"   调试信息：{login_check.stdout[:200]}")
        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']}篇笔记)")
            
            # 间隔 2 秒，避免触发风控
            time.sleep(2)
        
        all_results[city] = city_results
        print(f"  ✓ {city} 完成")
    
    # 保存结果
    output_file = Path(__file__).parent / "data" / "shandong_guobao_jinan_qingdao_p2-6-1.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())
