#!/usr/bin/env python3
"""
台股投研系統成本計算器
比較不同 AI 方案的實際成本
"""

def calculate_dikw_costs():
    """計算 DIKW 直接 API 成本"""
    print("🧮 DIKW 直接 API 成本分析")
    print("=" * 40)
    
    # 每日 token 使用估算
    daily_usage = {
        'data_collection': {
            'tokens': 2000,  # Haiku - 抓取和分析新聞
            'model': 'claude-3-5-haiku-20241022',
            'input_price': 0.80,  # per 1M tokens
            'output_price': 4.00
        },
        'info_knowledge': {
            'tokens': 8000,  # Sonnet - 生成晨報和分析
            'model': 'claude-3-5-sonnet-20241022', 
            'input_price': 3.00,
            'output_price': 15.00
        },
        'wisdom': {
            'tokens': 3000,  # Opus - 僅用戶選 3 時 (估計 20% 使用率)
            'model': 'claude-3-opus-20240229',
            'input_price': 15.00,
            'output_price': 75.00,
            'usage_rate': 0.2  # 20% 的時間會用到
        }
    }
    
    daily_cost = 0
    for layer, config in daily_usage.items():
        tokens = config['tokens']
        if 'usage_rate' in config:
            tokens *= config['usage_rate']
            
        # 假設 input:output = 3:1
        input_tokens = tokens * 0.75
        output_tokens = tokens * 0.25
        
        cost = (input_tokens/1000000 * config['input_price'] + 
                output_tokens/1000000 * config['output_price'])
        
        daily_cost += cost
        
        print(f"{layer:15} | {config['model'][:20]:20} | ${cost:.4f}/day")
    
    monthly_cost = daily_cost * 30
    
    print("-" * 60)
    print(f"{'每日成本':15} | ${daily_cost:.4f}")
    print(f"{'每月成本':15} | ${monthly_cost:.2f}")
    print(f"{'年度成本':15} | ${monthly_cost * 12:.2f}")
    
    return monthly_cost

def calculate_copilot_cost():
    """計算 GitHub Copilot 成本"""
    print("\n🤖 GitHub Copilot 成本")
    print("=" * 30)
    print("月費: $10.00 (固定)")
    print("年費: $120.00")
    print("優勢: 無 token 限制，三模型混用")
    print("劣勢: 不透明，未測試台股效果")
    
    return 10.00

def calculate_free_alternatives():
    """計算免費替代方案成本"""
    print("\n🆓 免費/低成本替代方案")
    print("=" * 35)
    
    alternatives = {
        "Gemini 1.5 Flash": {
            "free_limit": "每月 1500 次",
            "paid_rate": "$0.075/M tokens",
            "estimated_monthly": "$0-2"
        },
        "OpenAI Free Tier": {
            "free_limit": "$5 credit",
            "paid_rate": "$2.50/M tokens", 
            "estimated_monthly": "$0-3"
        },
        "本地 Ollama": {
            "free_limit": "無限",
            "paid_rate": "僅電費",
            "estimated_monthly": "$0-1"
        },
        "規則引擎 + 少量AI": {
            "free_limit": "80% 規則處理",
            "paid_rate": "僅複雜判斷用 AI",
            "estimated_monthly": "$1-3"
        }
    }
    
    for name, info in alternatives.items():
        print(f"{name:20} | {info['free_limit']:15} | {info['estimated_monthly']}")
    
    return 1.5  # 平均成本

def show_comparison():
    """顯示全方案比較"""
    print("\n📊 全方案成本比較")
    print("=" * 50)
    
    dikw_cost = calculate_dikw_costs()
    copilot_cost = calculate_copilot_cost() 
    free_cost = calculate_free_alternatives()
    
    print("\n🏆 方案排名 (按成本)")
    print("-" * 30)
    
    options = [
        ("免費/低成本方案", free_cost),
        ("DIKW 直接 API", dikw_cost),
        ("GitHub Copilot", copilot_cost)
    ]
    
    options.sort(key=lambda x: x[1])
    
    for i, (name, cost) in enumerate(options, 1):
        savings = ""
        if i == 1:
            baseline = cost
        else:
            save_amount = cost - baseline
            save_percent = (save_amount / cost) * 100
            savings = f" (+${save_amount:.2f}, +{save_percent:.0f}%)"
        
        print(f"{i}. {name:20} ${cost:6.2f}/月{savings}")

def calculate_breakeven():
    """計算損益平衡點"""
    print("\n⚖️  損益平衡分析")
    print("=" * 25)
    
    copilot_monthly = 10.00
    dikw_daily = 0.026  # 從上面計算得出
    
    print(f"Copilot 固定費用: ${copilot_monthly:.2f}/月")
    print(f"DIKW 每日成本: ${dikw_daily:.3f}")
    print(f"DIKW 每月成本 (30天): ${dikw_daily * 30:.2f}")
    
    # 計算多少使用量下 Copilot 划算
    breakeven_days = copilot_monthly / dikw_daily
    print(f"\n損益平衡點: {breakeven_days:.0f} 天/月")
    print(f"結論: 如果每月使用 >{breakeven_days:.0f} 天，Copilot 較划算")
    print(f"      如果每月使用 <{breakeven_days:.0f} 天，DIKW 直接 API 較划算")
    
    # 我們的使用情境
    our_usage = 30  # 每天都用
    if our_usage > breakeven_days:
        print(f"\n✅ 我們的使用情境 ({our_usage} 天/月): Copilot 較適合")
    else:
        print(f"\n✅ 我們的使用情境 ({our_usage} 天/月): DIKW 直接 API 較適合")

def show_quality_comparison():
    """顯示品質比較"""
    print("\n🎯 品質 vs 成本分析")
    print("=" * 30)
    
    comparison = [
        ["方案", "月成本", "AI品質", "可控性", "透明度", "測試狀態"],
        ["DIKW直接API", "$0.78", "⭐⭐⭐⭐⭐", "⭐⭐⭐⭐⭐", "⭐⭐⭐⭐⭐", "✅可測試"],
        ["GitHub Copilot", "$10.00", "⭐⭐⭐⭐⭐", "⭐⭐", "⭐⭐", "❓未知"],
        ["免費方案", "$1.50", "⭐⭐⭐", "⭐⭐⭐⭐", "⭐⭐⭐⭐", "✅可測試"],
        ["本地模型", "$0.50", "⭐⭐⭐⭐", "⭐⭐⭐⭐⭐", "⭐⭐⭐⭐⭐", "✅可測試"]
    ]
    
    for row in comparison:
        print(f"{row[0]:12} | {row[1]:8} | {row[2]:10} | {row[3]:10} | {row[4]:10} | {row[5]}")

def main():
    """主程序"""
    print("🦉 台股投研系統 - AI 成本計算器")
    print("=" * 45)
    
    show_comparison()
    calculate_breakeven() 
    show_quality_comparison()
    
    print("\n💡 建議")
    print("=" * 15)
    print("1. 🏆 推薦：DIKW 直接 API")
    print("   - 成本最優化 ($0.78/月)")
    print("   - 品質有保證 (Claude 系列)")
    print("   - 完全可控和透明")
    print("   - 立即可測試")
    
    print("\n2. 🥈 備選：免費混合方案")
    print("   - 超低成本 ($1.50/月)")
    print("   - 需要更多開發工作")
    print("   - 適合技術探索")
    
    print("\n3. ⚠️  GitHub Copilot")
    print("   - 成本最高 ($10/月)")
    print("   - 品質未知 (未測試)")
    print("   - 黑盒操作")
    print("   - 需要額外訂閱")

if __name__ == "__main__":
    main()