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


class IStorage(Protocol):
    def add(self, request: TrackedRequest) -> None:
        ...

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

    def clear(self) -> None:
        ...


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 = []
        for req in self.requests:
            req_copy = req.copy()
            if "timestamp" in req_copy and hasattr(req_copy["timestamp"], "isoformat"):
                req_copy["timestamp"] = req_copy["timestamp"].isoformat()
            serializable_requests.append(req_copy)

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

    def load(self) -> None:
        if os.path.exists(self.file_path):
            with open(self.file_path, "r") as f:
                self.requests = json.load(f)

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