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

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

# 潍坊 + 淄博待核实清单（剩余 22 处）
GUOBAO_TO_VERIFY = {
    "潍坊": [
        "棣花古镇", "范公亭", "偶园", "潍坊风筝博物馆",
        "杨家埠民间艺术大观园", "青州古城墙", "龙兴寺遗址",
        "山旺古生物化石", "郑公祠", "莫言旧居",
        "齐长城遗址", "寿光纪台", "昌邑故城"
    ],
    "淄博": [
        "齐文化博物馆", "沂源溶洞", "中国陶瓷馆", "周村烧饼博物馆",
        "开元寺", "蒲松龄墓", "后李遗址", "桐林遗址",
        "田齐王陵"
    ]
}


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')
        
        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-3：山东国保核实 - 潍坊 + 淄博（剩余 22 处）")
    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("❌ 小红书未登录")
        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(1)
        
        all_results[city] = city_results
        print(f"  ✓ {city} 完成")
    
    output_file = Path(__file__).parent / "data" / "shandong_guobao_weifang_zibo_p2-6-3.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())
