#!/usr/bin/env python3
"""
📊 即時綜合監控面板 - Realtime Dashboard
包含：資金狀況、期貨持倉、實體庫存
"""

import datetime
import json
import os
import time
from typing import Dict, List

class RealtimeDashboard:
    def __init__(self):
        self.capital = {
            'TWD': {'country': '🇹🇼 台灣', 'amount': 1000000, 'usd_equiv': 31250},
            'JPY': {'country': '🇯🇵 日本', 'amount': 150000, 'usd_equiv': 1000},
            'USD': {'country': '🇺🇸 美國', 'amount': 10000, 'usd_equiv': 10000},
            'CNY': {'country': '🇨🇳 中國', 'amount': 5000, 'usd_equiv': 690}
        }
        
        self.futures_positions = {
            'commodities': [],
            'forex': []
        }
        
        self.inventory = {
            'warehouses': {},
            'in_transit': [],
            'sales_data': {}
        }
        
        self.load_data()
    
    def load_data(self):
        """載入最新數據"""
        # 模擬數據載入
        self.update_capital()
        self.update_futures()
        self.update_inventory()
    
    def update_capital(self):
        """更新各國資金狀況"""
        # 模擬資金變動
        self.capital['TWD']['amount'] = 850000  # 使用了15萬台幣
        self.capital['TWD']['usd_equiv'] = 26562
        self.capital['USD']['amount'] = 12180  # 賺了2180美金
        self.capital['USD']['usd_equiv'] = 12180
        
    def update_futures(self):
        """更新期貨持倉"""
        self.futures_positions = {
            'commodities': [
                {'symbol': 'GC', 'name': '黃金期貨', 'contracts': 2, 'entry': 2050.5, 'current': 2055.3, 'pnl': +960},
                {'symbol': 'CL', 'name': '原油期貨', 'contracts': 1, 'entry': 71.20, 'current': 70.85, 'pnl': -350},
                {'symbol': 'HG', 'name': '銅期貨', 'contracts': 3, 'entry': 4.285, 'current': 4.312, 'pnl': +2025},
            ],
            'forex': [
                {'pair': 'USD/JPY', 'size': 10000, 'entry': 154.80, 'current': 154.95, 'pnl': +150},
                {'pair': 'EUR/USD', 'size': -5000, 'entry': 1.0892, 'current': 1.0885, 'pnl': +35},
            ]
        }
    
    def update_inventory(self):
        """更新實體庫存"""
        self.inventory = {
            'warehouses': {
                '台灣桃園倉': {
                    'location': '🇹🇼 桃園',
                    'items': [
                        {'product': 'GaN充電器', 'quantity': 500, 'value': 4250},
                        {'product': '無線耳機', 'quantity': 200, 'value': 2400}
                    ],
                    'total_value': 6650
                },
                '美國LA倉': {
                    'location': '🇺🇸 洛杉磯',
                    'items': [
                        {'product': 'GaN充電器', 'quantity': 300, 'value': 8997},
                        {'product': '手機支架', 'quantity': 1000, 'value': 9990}
                    ],
                    'total_value': 18987
                },
                '中國深圳倉': {
                    'location': '🇨🇳 深圳',
                    'items': [
                        {'product': '工業軸承', 'quantity': 2000, 'value': 10000},
                        {'product': '電子零件', 'quantity': 5000, 'value': 3500}
                    ],
                    'total_value': 13500
                }
            },
            'in_transit': [
                {
                    'shipment_id': 'MSKU1234567',
                    'route': '深圳→LA',
                    'product': 'GaN充電器',
                    'quantity': 1000,
                    'eta': '2026-04-05',
                    'days_remaining': 17,
                    'value': 8500
                },
                {
                    'shipment_id': 'EVG9876543',
                    'route': '台灣→東京',
                    'product': '精密儀器',
                    'quantity': 50,
                    'eta': '2026-03-25',
                    'days_remaining': 6,
                    'value': 15000
                }
            ],
            'sales_data': {
                'today': {
                    'units_sold': 47,
                    'revenue': 1403.53,
                    'top_product': 'GaN充電器'
                },
                'week': {
                    'units_sold': 312,
                    'revenue': 9315.20,
                    'growth': '+12.5%'
                },
                'month': {
                    'units_sold': 1847,
                    'revenue': 55410.00,
                    'growth': '+28.3%'
                }
            }
        }
    
    def display_dashboard(self):
        """顯示完整面板"""
        os.system('clear' if os.name == 'posix' else 'cls')
        
        print("=" * 80)
        print(f"📊 即時綜合監控面板 | {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print("=" * 80)
        
        # 1. 各國資金狀況
        self.display_capital()
        
        # 2. 期貨持倉
        self.display_futures()
        
        # 3. 實體庫存
        self.display_inventory()
        
        # 4. 銷售數據
        self.display_sales()
        
        print("=" * 80)
        print("💡 按 Ctrl+C 退出 | 每5秒自動更新")
    
    def display_capital(self):
        """顯示各國資金"""
        print("\n💰 【各國資金狀況】")
        print("-" * 60)
        
        total_usd = 0
        for currency, data in self.capital.items():
            total_usd += data['usd_equiv']
            status = "✅" if data['amount'] > 0 else "⚠️"
            print(f"  {status} {data['country']}: {currency} {data['amount']:,.0f} (≈ ${data['usd_equiv']:,.0f})")
        
        print(f"\n  📊 總資產: ${total_usd:,.0f} USD")
        profit = total_usd - 42940
        profit_pct = (profit / 42940) * 100
        if profit >= 0:
            print(f"  📈 總收益: +${profit:,.0f} (+{profit_pct:.1f}%)")
        else:
            print(f"  📉 總虧損: ${profit:,.0f} ({profit_pct:.1f}%)")
    
    def display_futures(self):
        """顯示期貨持倉"""
        print("\n📈 【期貨持倉狀況】")
        print("-" * 60)
        
        # 商品期貨
        print("  商品期貨:")
        total_commodity_pnl = 0
        for position in self.futures_positions['commodities']:
            total_commodity_pnl += position['pnl']
            icon = "🟢" if position['pnl'] >= 0 else "🔴"
            print(f"    {icon} {position['name']}: {position['contracts']}口 @ {position['entry']}")
            print(f"       現價: {position['current']} | P/L: ${position['pnl']:+,.0f}")
        
        # 外匯期貨
        print("\n  外匯部位:")
        total_forex_pnl = 0
        for position in self.futures_positions['forex']:
            total_forex_pnl += position['pnl']
            icon = "🟢" if position['pnl'] >= 0 else "🔴"
            direction = "買" if position['size'] > 0 else "賣"
            print(f"    {icon} {position['pair']}: {direction} {abs(position['size']):,}")
            print(f"       入場: {position['entry']} → {position['current']} | P/L: ${position['pnl']:+,.0f}")
        
        total_futures_pnl = total_commodity_pnl + total_forex_pnl
        print(f"\n  💼 期貨總損益: ${total_futures_pnl:+,.0f}")
    
    def display_inventory(self):
        """顯示實體庫存"""
        print("\n📦 【實體庫存狀況】")
        print("-" * 60)
        
        # 倉庫庫存
        print("  倉庫庫存:")
        total_inventory_value = 0
        for warehouse, data in self.inventory['warehouses'].items():
            total_inventory_value += data['total_value']
            print(f"\n    📍 {warehouse} {data['location']}")
            for item in data['items']:
                print(f"      • {item['product']}: {item['quantity']}件 (${item['value']:,.0f})")
            print(f"      💵 倉庫總值: ${data['total_value']:,.0f}")
        
        # 在途貨物
        print("\n  🚢 在途貨物:")
        total_transit_value = 0
        for shipment in self.inventory['in_transit']:
            total_transit_value += shipment['value']
            print(f"    • [{shipment['shipment_id']}] {shipment['route']}")
            print(f"      {shipment['product']} x{shipment['quantity']} | 價值: ${shipment['value']:,.0f}")
            print(f"      ETA: {shipment['eta']} ({shipment['days_remaining']}天)")
        
        print(f"\n  📊 庫存總值: ${total_inventory_value:,.0f}")
        print(f"  🚚 在途總值: ${total_transit_value:,.0f}")
        print(f"  💰 實體資產: ${total_inventory_value + total_transit_value:,.0f}")
    
    def display_sales(self):
        """顯示銷售數據"""
        print("\n💹 【銷售數據】")
        print("-" * 60)
        
        sales = self.inventory['sales_data']
        
        print(f"  今日銷售:")
        print(f"    • 售出: {sales['today']['units_sold']}件")
        print(f"    • 營收: ${sales['today']['revenue']:,.2f}")
        print(f"    • 熱銷: {sales['today']['top_product']}")
        
        print(f"\n  本週累計:")
        print(f"    • 售出: {sales['week']['units_sold']}件")
        print(f"    • 營收: ${sales['week']['revenue']:,.2f}")
        print(f"    • 成長: {sales['week']['growth']}")
        
        print(f"\n  本月累計:")
        print(f"    • 售出: {sales['month']['units_sold']}件")
        print(f"    • 營收: ${sales['month']['revenue']:,.2f}")
        print(f"    • 成長: {sales['month']['growth']}")
    
    def run(self):
        """運行即時監控"""
        try:
            while True:
                self.load_data()  # 更新數據
                self.display_dashboard()  # 顯示面板
                time.sleep(5)  # 每5秒更新
        except KeyboardInterrupt:
            print("\n\n👋 監控面板已停止")

if __name__ == "__main__":
    dashboard = RealtimeDashboard()
    dashboard.run()