#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API 響應處理工具

Author: PANJIT IT Team  
Created: 2025-09-02
"""

from datetime import datetime
from typing import Dict, Any, List, Union
from app.utils.timezone import to_taiwan_time, format_taiwan_time


def convert_datetime_to_taiwan(data: Union[Dict, List, Any]) -> Union[Dict, List, Any]:
    """遞迴轉換資料中的 datetime 欄位為台灣時間
    
    Args:
        data: 要轉換的資料（字典、列表或其他）
        
    Returns:
        轉換後的資料
    """
    if isinstance(data, dict):
        result = {}
        for key, value in data.items():
            if isinstance(value, datetime):
                # 將 datetime 轉換為台灣時間的 ISO 字符串
                taiwan_dt = to_taiwan_time(value)
                result[key] = taiwan_dt.isoformat()
            elif key in ['created_at', 'updated_at', 'completed_at', 'processing_started_at', 'last_login', 'timestamp']:
                # 特定的時間欄位
                if isinstance(value, str):
                    try:
                        # 嘗試解析 ISO 格式的時間字符串
                        dt = datetime.fromisoformat(value.replace('Z', '+00:00'))
                        taiwan_dt = to_taiwan_time(dt)
                        result[key] = taiwan_dt.isoformat()
                    except:
                        result[key] = value
                else:
                    result[key] = convert_datetime_to_taiwan(value)
            else:
                result[key] = convert_datetime_to_taiwan(value)
        return result
    elif isinstance(data, list):
        return [convert_datetime_to_taiwan(item) for item in data]
    else:
        return data


def create_taiwan_response(success: bool = True, data: Any = None, message: str = '', 
                          error: str = '', **kwargs) -> Dict[str, Any]:
    """創建包含台灣時區轉換的 API 響應
    
    Args:
        success: 是否成功
        data: 響應資料
        message: 成功訊息
        error: 錯誤訊息
        **kwargs: 其他參數
        
    Returns:
        包含台灣時區的響應字典
    """
    response = {
        'success': success,
        'timestamp': format_taiwan_time(datetime.now(), "%Y-%m-%d %H:%M:%S")
    }
    
    if data is not None:
        response['data'] = convert_datetime_to_taiwan(data)
    
    if message:
        response['message'] = message
        
    if error:
        response['error'] = error
        
    # 加入其他參數
    for key, value in kwargs.items():
        response[key] = convert_datetime_to_taiwan(value)
    
    return response