
# -*- coding: utf-8 -*-
"""
车辆实时数据管理器
"""

import json
import logging
from typing import List, Dict, Any, Optional
from datetime import datetime, timedelta
from sqlalchemy import desc

from ..core.database import db_manager
from ..core.models import VehicleData

logger = logging.getLogger(__name__)

class VehicleDataManager:
    """车辆实时数据管理器"""
    
    def __init__(self):
        self.logger = logger
    
    def add_vehicle_data(
        self,
        vehicle_id: str,
        data_type: str,
        data_value: Dict[str, Any],
        vehicle_vin: str = None
    ) -> bool:
        """添加车辆实时数据"""
        try:
            with db_manager.get_session() as session:
                vehicle_data = VehicleData(
                    vehicle_id=vehicle_id,
                    vehicle_vin=vehicle_vin,
                    data_type=data_type,
                    data_value=json.dumps(data_value, ensure_ascii=False),
                    timestamp=datetime.now()
                )
                session.add(vehicle_data)
                session.commit()
                
                logger.info(f"添加车辆数据成功: {vehicle_id} - {data_type}")
                return True
                
        except Exception as e:
            logger.error(f"添加车辆数据失败: {e}")
            return False
    
    def get_vehicle_data(
        self,
        vehicle_id: str,
        data_type: str = None,
        limit: int = 10
    ) -> List[Dict[str, Any]]:
        """获取车辆实时数据"""
        try:
            with db_manager.get_session() as session:
                query = session.query(VehicleData).filter(
                    VehicleData.vehicle_id == vehicle_id,
                    VehicleData.is_active == True
                )
                
                if data_type:
                    query = query.filter(VehicleData.data_type == data_type)
                
                vehicle_data_list = query.order_by(desc(VehicleData.timestamp)).limit(limit).all()
                
                results = []
                for data in vehicle_data_list:
                    try:
                        data_value = json.loads(data.data_value)
                    except:
                        data_value = data.data_value
                    
                    results.append({
                        "id": data.id,
                        "vehicle_id": data.vehicle_id,
                        "vehicle_vin": data.vehicle_vin,
                        "data_type": data.data_type,
                        "data_value": data_value,
                        "timestamp": data.timestamp.isoformat(),
                        "is_active": data.is_active
                    })
                
                return results
                
        except Exception as e:
            logger.error(f"获取车辆数据失败: {e}")
            return []

    def get_vehicle_data_by_vin(
        self,
        vehicle_vin: str,
        data_type: str = None,
        limit: int = 10
    ) -> List[Dict[str, Any]]:
        """按VIN获取车辆实时数据"""
        try:
            with db_manager.get_session() as session:
                query = session.query(VehicleData).filter(
                    VehicleData.vehicle_vin == vehicle_vin,
                    VehicleData.is_active == True
                )
                if data_type:
                    query = query.filter(VehicleData.data_type == data_type)
                vehicle_data_list = query.order_by(desc(VehicleData.timestamp)).limit(limit).all()

                results = []
                for data in vehicle_data_list:
                    try:
                        data_value = json.loads(data.data_value)
                    except:
                        data_value = data.data_value
                    results.append({
                        "id": data.id,
                        "vehicle_id": data.vehicle_id,
                        "vehicle_vin": data.vehicle_vin,
                        "data_type": data.data_type,
                        "data_value": data_value,
                        "timestamp": data.timestamp.isoformat(),
                        "is_active": data.is_active
                    })
                return results
        except Exception as e:
            logger.error(f"按VIN获取车辆数据失败: {e}")
            return []
    
    def get_latest_vehicle_data(self, vehicle_id: str) -> Dict[str, Any]:
        """获取车辆最新数据"""
        try:
            with db_manager.get_session() as session:
                # 获取各种类型的最新数据
                data_types = ['location', 'status', 'fault', 'battery', 'engine']
                latest_data = {}
                
                for data_type in data_types:
                    data = session.query(VehicleData).filter(
                        VehicleData.vehicle_id == vehicle_id,
                        VehicleData.data_type == data_type,
                        VehicleData.is_active == True
                    ).order_by(desc(VehicleData.timestamp)).first()
                    
                    if data:
                        try:
                            data_value = json.loads(data.data_value)
                        except:
                            data_value = data.data_value
                        
                        latest_data[data_type] = {
                            "value": data_value,
                            "timestamp": data.timestamp.isoformat()
                        }
                
                return latest_data
                
        except Exception as e:
            logger.error(f"获取车辆最新数据失败: {e}")
            return {}

    def get_latest_vehicle_data_by_vin(self, vehicle_vin: str) -> Dict[str, Any]:
        """按VIN获取车辆最新数据"""
        try:
            with db_manager.get_session() as session:
                data_types = ['location', 'status', 'fault', 'battery', 'engine']
                latest_data: Dict[str, Any] = {}
                for data_type in data_types:
                    data = session.query(VehicleData).filter(
                        VehicleData.vehicle_vin == vehicle_vin,
                        VehicleData.data_type == data_type,
                        VehicleData.is_active == True
                    ).order_by(desc(VehicleData.timestamp)).first()
                    if data:
                        try:
                            data_value = json.loads(data.data_value)
                        except:
                            data_value = data.data_value
                        latest_data[data_type] = {
                            "value": data_value,
                            "timestamp": data.timestamp.isoformat(),
                            "vehicle_id": data.vehicle_id,
                            "vehicle_vin": data.vehicle_vin
                        }
                return latest_data
        except Exception as e:
            logger.error(f"按VIN获取车辆最新数据失败: {e}")
            return {}
    
    def search_vehicle_data(
        self,
        vehicle_id: str = None,
        data_type: str = None,
        start_time: datetime = None,
        end_time: datetime = None,
        limit: int = 100
    ) -> List[Dict[str, Any]]:
        """搜索车辆数据"""
        try:
            with db_manager.get_session() as session:
                query = session.query(VehicleData).filter(VehicleData.is_active == True)
                
                if vehicle_id:
                    query = query.filter(VehicleData.vehicle_id == vehicle_id)
                
                if data_type:
                    query = query.filter(VehicleData.data_type == data_type)
                
                if start_time:
                    query = query.filter(VehicleData.timestamp >= start_time)
                
                if end_time:
                    query = query.filter(VehicleData.timestamp <= end_time)
                
                vehicle_data_list = query.order_by(desc(VehicleData.timestamp)).limit(limit).all()
                
                results = []
                for data in vehicle_data_list:
                    try:
                        data_value = json.loads(data.data_value)
                    except:
                        data_value = data.data_value
                    
                    results.append({
                        "id": data.id,
                        "vehicle_id": data.vehicle_id,
                        "vehicle_vin": data.vehicle_vin,
                        "data_type": data.data_type,
                        "data_value": data_value,
                        "timestamp": data.timestamp.isoformat(),
                        "is_active": data.is_active
                    })
                
                return results
                
        except Exception as e:
            logger.error(f"搜索车辆数据失败: {e}")
            return []
    
    def add_sample_vehicle_data(self) -> bool:
        """添加示例车辆数据"""
        try:
            sample_data = [
                {
                    "vehicle_id": "V001",
                    "vehicle_vin": "LSGBF53E8DH123456",
                    "data_type": "location",
                    "data_value": {
                        "latitude": 39.9042,
                        "longitude": 116.4074,
                        "address": "北京市朝阳区",
                        "speed": 0,
                        "direction": 0
                    }
                },
                {
                    "vehicle_id": "V001",
                    "vehicle_vin": "LSGBF53E8DH123456",
                    "data_type": "status",
                    "data_value": {
                        "engine_status": "off",
                        "door_status": "locked",
                        "window_status": "closed",
                        "light_status": "off",
                        "air_conditioning": "off"
                    }
                },
                {
                    "vehicle_id": "V001",
                    "vehicle_vin": "LSGBF53E8DH123456",
                    "data_type": "battery",
                    "data_value": {
                        "battery_level": 85,
                        "charging_status": "not_charging",
                        "estimated_range": 320,
                        "battery_health": "good"
                    }
                },
                {
                    "vehicle_id": "V001",
                    "vehicle_vin": "LSGBF53E8DH123456",
                    "data_type": "engine",
                    "data_value": {
                        "engine_temperature": 45,
                        "oil_level": "normal",
                        "fuel_level": 75,
                        "mileage": 12580
                    }
                },
                {
                    "vehicle_id": "V002",
                    "vehicle_vin": "LSGBF53E8DH123457",
                    "data_type": "location",
                    "data_value": {
                        "latitude": 31.2304,
                        "longitude": 121.4737,
                        "address": "上海市黄浦区",
                        "speed": 25,
                        "direction": 90
                    }
                },
                {
                    "vehicle_id": "V002",
                    "vehicle_vin": "LSGBF53E8DH123457",
                    "data_type": "status",
                    "data_value": {
                        "engine_status": "on",
                        "door_status": "unlocked",
                        "window_status": "open",
                        "light_status": "on",
                        "air_conditioning": "on"
                    }
                },
                {
                    "vehicle_id": "V002",
                    "vehicle_vin": "LSGBF53E8DH123457",
                    "data_type": "fault",
                    "data_value": {
                        "fault_codes": ["P0301", "P0171"],
                        "fault_descriptions": ["气缸1失火", "系统过稀"],
                        "severity": "medium",
                        "last_occurrence": "2024-09-06T10:30:00"
                    }
                }
            ]
            
            for data in sample_data:
                self.add_vehicle_data(
                    vehicle_id=data["vehicle_id"],
                    data_type=data["data_type"],
                    data_value=data["data_value"],
                    vehicle_vin=data["vehicle_vin"]
                )
            
            logger.info("示例车辆数据添加成功")
            return True
            
        except Exception as e:
            logger.error(f"添加示例车辆数据失败: {e}")
            return False
    
    def get_vehicle_summary(self, vehicle_id: str) -> Dict[str, Any]:
        """获取车辆数据摘要"""
        try:
            latest_data = self.get_latest_vehicle_data(vehicle_id)
            
            summary = {
                "vehicle_id": vehicle_id,
                "last_update": None,
                "status": "unknown",
                "location": None,
                "battery_level": None,
                "fault_count": 0,
                "data_types": list(latest_data.keys())
            }
            
            if latest_data:
                # 获取最新更新时间
                timestamps = [data["timestamp"] for data in latest_data.values()]
                if timestamps:
                    summary["last_update"] = max(timestamps)
                
                # 获取位置信息
                if "location" in latest_data:
                    summary["location"] = latest_data["location"]["value"]
                
                # 获取电池信息
                if "battery" in latest_data:
                    summary["battery_level"] = latest_data["battery"]["value"].get("battery_level")
                
                # 获取故障信息
                if "fault" in latest_data:
                    fault_codes = latest_data["fault"]["value"].get("fault_codes", [])
                    summary["fault_count"] = len(fault_codes)
                
                # 获取状态信息
                if "status" in latest_data:
                    engine_status = latest_data["status"]["value"].get("engine_status")
                    summary["status"] = "running" if engine_status == "on" else "stopped"
            
            return summary
            
        except Exception as e:
            logger.error(f"获取车辆摘要失败: {e}")
            return {"vehicle_id": vehicle_id, "error": str(e)}
