"""Flight recorder - logs all requests to JSON"""

import json
from datetime import datetime
from pathlib import Path


class FlightLogger:
    """Logs all HTTP requests to a JSON file (flight_log.json)"""
    
    def __init__(self, log_file: str = "flight_log.json"):
        self.log_file = Path(log_file)
        self.entries = []
        
        # Load existing logs if file exists
        if self.log_file.exists():
            try:
                with open(self.log_file, 'r') as f:
                    self.entries = json.load(f)
            except (json.JSONDecodeError, IOError):
                self.entries = []
    
    def log_request(
        self,
        method: str,
        url: str,
        status: int = None,
        blocked: bool = False,
        allowed: bool = True,
        estimated_cost: float = 0.0,
        **kwargs
    ):
        """Log a single request"""
        entry = {
            "timestamp": datetime.utcnow().isoformat(),
            "method": method,
            "url": url,
            "status": status,
            "blocked": blocked,
            "allowed": allowed,
            "estimated_cost": estimated_cost,
            **kwargs
        }
        self.entries.append(entry)
        self._save()
    
    def _save(self):
        """Save entries to JSON file"""
        try:
            with open(self.log_file, 'w') as f:
                json.dump(self.entries, f, indent=2)
        except IOError:
            # If we can't write, continue silently
            pass
    
    def get_total_cost(self) -> float:
        """Get total estimated cost from all logged requests"""
        return sum(entry.get("estimated_cost", 0.0) for entry in self.entries)
