#!/usr/bin/env python3
"""
📝 執行動作追蹤器 - Action Tracker
追蹤所有實際執行的交易動作
"""

import datetime
import json
import os

class ActionTracker:
    def __init__(self):
        self.log_file = "actions.log"
        self.json_file = "actions.json"
        
    def log_action(self, action_type, details):
        """記錄執行動作"""
        timestamp = datetime.datetime.now()
        
        # 寫入日誌檔
        with open(self.log_file, 'a') as f:
            f.write(f"[{timestamp.strftime('%Y-%m-%d %H:%M:%S')}] {action_type}: {details}\n")
        
        # 寫入JSON結構化數據
        action_data = {
            'timestamp': timestamp.isoformat(),
            'type': action_type,
            'details': details,
            'status': 'executed'
        }
        
        # 載入現有動作
        if os.path.exists(self.json_file):
            with open(self.json_file, 'r') as f:
                actions = json.load(f)
        else:
            actions = []
        
        actions.append(action_data)
        
        # 只保留最近100個動作
        if len(actions) > 100:
            actions = actions[-100:]
        
        with open(self.json_file, 'w') as f:
            json.dump(actions, f, indent=2)
        
        return action_data
    
    def show_recent_actions(self, limit=10):
        """顯示最近的執行動作"""
        print("\n📝 最近執行動作 (Recent Actions)")
        print("=" * 60)
        
        if os.path.exists(self.json_file):
            with open(self.json_file, 'r') as f:
                actions = json.load(f)
                
            # 顯示最近N個動作
            for action in actions[-limit:]:
                time = datetime.datetime.fromisoformat(action['timestamp'])
                print(f"\n⏰ {time.strftime('%H:%M:%S')}")
                print(f"   類型: {action['type']}")
                print(f"   詳情: {action['details']}")
                print(f"   狀態: {action.get('status', 'unknown')}")
        else:
            print("沒有執行記錄")
    
    def show_today_summary(self):
        """顯示今日執行總結"""
        print("\n📊 今日執行總結")
        print("=" * 60)
        
        if os.path.exists(self.json_file):
            with open(self.json_file, 'r') as f:
                actions = json.load(f)
            
            today = datetime.date.today()
            today_actions = [
                a for a in actions 
                if datetime.datetime.fromisoformat(a['timestamp']).date() == today
            ]
            
            # 統計各類動作
            action_counts = {}
            for action in today_actions:
                action_type = action['type']
                action_counts[action_type] = action_counts.get(action_type, 0) + 1
            
            print(f"📅 日期: {today}")
            print(f"📈 總執行: {len(today_actions)} 個動作")
            print("\n分類統計:")
            for action_type, count in action_counts.items():
                print(f"   • {action_type}: {count} 次")
            
            # 顯示最新5個
            print("\n最近5個動作:")
            for action in today_actions[-5:]:
                time = datetime.datetime.fromisoformat(action['timestamp'])
                print(f"   [{time.strftime('%H:%M')}] {action['type']}: {action['details'][:50]}...")
        else:
            print("今日無執行記錄")

# 模擬一些動作記錄
def simulate_actions():
    """模擬執行動作（測試用）"""
    tracker = ActionTracker()
    
    # 模擬不同類型的動作
    sample_actions = [
        ('TRADE_EXECUTED', 'USD/JPY 買入 10,000 @ 154.80'),
        ('SEED_DISCOVERED', '發現新種子: GaN充電器, 預期收益 43%'),
        ('RESEARCH_COMPLETE', '完成深度研究: 工業軸承供應商驗證'),
        ('ORDER_PLACED', '下單: 500個充電器 from 深圳XX科技'),
        ('RISK_ALERT', '止損觸發: EUR/USD position closed'),
        ('PROFIT_TAKEN', '獲利了結: +$247 from 早盤外匯交易'),
    ]
    
    # 記錄動作
    for action_type, details in sample_actions[:3]:  # 只記錄前3個作為示例
        tracker.log_action(action_type, details)
        print(f"✅ 記錄: {action_type}")
    
    return tracker

if __name__ == "__main__":
    # 初始化追蹤器
    tracker = ActionTracker()
    
    # 如果沒有記錄，先模擬一些
    if not os.path.exists('actions.json'):
        print("初始化動作追蹤器...")
        tracker = simulate_actions()
        print()
    
    # 顯示最近動作
    tracker.show_recent_actions(5)
    
    # 顯示今日總結
    tracker.show_today_summary()