#!/usr/bin/env python3
"""
台股投研系統設定驗證工具
檢查所有必要組件是否正確設定
"""

import os
import json

def check_github_repo():
    """檢查 GitHub Repository 狀態"""
    print("🔍 檢查 GitHub Repository...")
    
    # 簡單檢查是否在正確目錄
    if os.path.exists('.github/workflows/morning-briefing.yml'):
        print("✅ GitHub Actions workflow 存在")
    else:
        print("❌ GitHub Actions workflow 不存在")
        return False
    
    if os.path.exists('data/watchlist'):
        watchlist_count = len([f for f in os.listdir('data/watchlist') if f.endswith('.yml')])
        print(f"✅ 觀察名單檔案: {watchlist_count} 檔")
    else:
        print("❌ 觀察名單目錄不存在")
        return False
    
    return True

def check_required_files():
    """檢查必要檔案"""
    print("\n📁 檢查必要檔案...")
    
    required_files = [
        'README.md',
        '.github/workflows/morning-briefing.yml',
        'scripts/dikw_fetch_news.py',
        'scripts/dikw_briefing.py', 
        'scripts/send_line.py',
        '.env.example'
    ]
    
    all_exist = True
    for file_path in required_files:
        if os.path.exists(file_path):
            print(f"✅ {file_path}")
        else:
            print(f"❌ {file_path}")
            all_exist = False
    
    return all_exist

def check_watchlist_structure():
    """檢查觀察名單結構"""
    print("\n📊 檢查觀察名單結構...")
    
    if not os.path.exists('data/watchlist'):
        print("❌ 觀察名單目錄不存在")
        return False
    
    watchlist_files = [f for f in os.listdir('data/watchlist') if f.endswith('.yml')]
    
    if len(watchlist_files) != 19:  # 台達電只計算一次
        print(f"⚠️ 觀察名單數量: {len(watchlist_files)} (預期: 19)")
    else:
        print(f"✅ 觀察名單數量: {len(watchlist_files)}")
    
    # 檢查產業分布
    industries = {'AI伺服器': 0, '半導體設備': 0, '記憶體': 0, '能源': 0}
    
    for file in watchlist_files:
        # 簡單的產業分類檢查
        if any(code in file for code in ['2382', '3231', '6669', '2356', '2308']):
            industries['AI伺服器'] += 1
        elif any(code in file for code in ['3680', '6196', '2404', '6139', '3413']):
            industries['半導體設備'] += 1
        elif any(code in file for code in ['2408', '2344', '8299', '3260', '2451']):
            industries['記憶體'] += 1
        elif any(code in file for code in ['1513', '1503', '1514', '2371']):
            industries['能源'] += 1
    
    print("產業分布:")
    for industry, count in industries.items():
        print(f"  {industry}: {count} 檔")
    
    return True

def generate_next_steps():
    """生成下一步操作指南"""
    print("\n🎯 下一步操作指南")
    print("=" * 40)
    
    steps = [
        "1. 訂閱 GitHub Copilot",
        "   https://github.com/settings/copilot",
        "",
        "2. 設定 LINE Bot (參考 LINE-Bot-Setup-Guide.md)",
        "   - 創建 Messaging API Channel",
        "   - 獲取 Channel Access Token", 
        "   - 獲取 Channel Secret",
        "   - 獲取 LINE User ID",
        "",
        "3. 設定 GitHub Secrets",
        "   https://github.com/JanWangg/taiwan-stock-research/settings/secrets/actions",
        "   - LINE_CHANNEL_ACCESS_TOKEN",
        "   - LINE_CHANNEL_SECRET", 
        "   - LINE_USER_ID",
        "",
        "4. 啟用 GitHub Actions", 
        "   https://github.com/JanWangg/taiwan-stock-research/actions",
        "",
        "5. 測試系統",
        "   - 手動觸發 workflow",
        "   - 檢查 LINE 是否收到測試訊息",
        "",
        "6. 等待明天 06:00 TST 第一份自動晨報！"
    ]
    
    for step in steps:
        print(step)

def show_cost_summary():
    """顯示成本摘要"""
    print("\n💰 成本摘要")
    print("=" * 20)
    print("GitHub Copilot:     $10/月")
    print("GitHub Actions:     $0 (免費)")
    print("GitHub Storage:     $0 (免費)")
    print("LINE Messaging API: $0 (免費)")
    print("-" * 20)
    print("總計:              $10/月")
    print()
    print("vs 原 OpenClaw 方案: $8-13/月")
    print("差異: +$2-7/月，但獲得:")
    print("  ✅ 3個頂尖模型 (Gemini + Claude + GPT)")
    print("  ✅ 無需管理 VPS")
    print("  ✅ GitHub 生態整合")
    print("  ✅ 更高可靠性")

def main():
    """主驗證流程"""
    print("🦉 台股投研系統設定驗證")
    print("=" * 30)
    
    # 檢查項目
    checks = [
        check_github_repo(),
        check_required_files(), 
        check_watchlist_structure()
    ]
    
    success_count = sum(checks)
    total_checks = len(checks)
    
    print(f"\n📋 驗證結果: {success_count}/{total_checks} 項目通過")
    
    if success_count == total_checks:
        print("🎉 系統檔案結構完整！")
        print("下一步：完成 LINE Bot 和 GitHub Copilot 設定")
    else:
        print("⚠️ 部分項目需要修正")
    
    # 顯示後續步驟
    generate_next_steps()
    show_cost_summary()
    
    print("\n📚 參考文件:")
    print("- LINE Bot 設定: LINE-Bot-Setup-Guide.md")
    print("- 手動設定: manual-setup.md") 
    print("- 完整文檔: GitHub-Stock-Research-System.md")

if __name__ == "__main__":
    main()