import json
from pathlib import Path
from typing import List, Optional
from .types import TrackedRequest, StorageOptions


class LocalStorage:
    def __init__(self, options: Optional[StorageOptions] = None):
        options = options or {}
        self.file_path = options.get("file_path", "./gemini-tracker-logs.json")
        self.auto_save = options.get("auto_save", True)
        self.requests: List[TrackedRequest] = []
        self.load()

    def add(self, request: TrackedRequest) -> None:
        self.requests.append(request)
        if self.auto_save:
            self.save()

    def get_all(self) -> List[TrackedRequest]:
        return self.requests.copy()

    def save(self) -> None:
        path = Path(self.file_path)
        path.parent.mkdir(parents=True, exist_ok=True)

        serializable_requests = [
            {**req, "timestamp": req["timestamp"].isoformat()}
            if "timestamp" in req and hasattr(req["timestamp"], "isoformat")
            else req
            for req in self.requests
        ]

        with open(self.file_path, "w") as f:
            json.dump(serializable_requests, f, indent=2, default=str)

    def load(self) -> None:
        path = Path(self.file_path)
        if path.exists():
            self.requests = json.loads(path.read_text())

    def clear(self) -> None:
        self.requests = []
