"""
File Driver - appends OCPP events to events.log file
"""
import json
import logging
import os
from datetime import datetime
from typing import Dict, Any, Optional

logger = logging.getLogger(__name__)


class FileDriver:
    """File-based OCPP driver - appends events to events.log"""
    
    def __init__(self):
        self.log_file = "events.log"
        logger.info(f"File driver initialized - logging to {self.log_file}")
        
    async def log_event(self, event_type: str, data: Dict[str, Any], source: str) -> Optional[Dict[str, Any]]:
        """Log an OCPP event to the events.log file"""
        try:
            # Create log entry
            log_entry = {
                "timestamp": datetime.utcnow().isoformat() + "Z",
                "event_type": event_type,
                "source": source,
                "data": data
            }
            
            # Append to events.log file
            with open(self.log_file, "a", encoding="utf-8") as f:
                f.write(json.dumps(log_entry) + "\n")
            
            logger.debug(f"[FILE] Logged {event_type} event from {source} to {self.log_file}")
            return {"status": "logged", "file": self.log_file, "event_type": event_type}
            
        except Exception as e:
            logger.error(f"[FILE] Failed to log event to {self.log_file}: {e}")
            return {"status": "error", "error": str(e)}
    
    async def send_message(self, charge_point_id: str, message: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        """Send/log a message - compatibility method"""
        action = message.get("action", "Unknown")
        data = message.get("data", message)
        return await self.log_event(action, data, charge_point_id)
