"""In-memory store implementations for pyfortis."""

from __future__ import annotations

import threading
from typing import Any

from pyfortis._types import BreachRecord, Position


class InMemoryPositionStore:
    """Thread-safe in-memory position store."""

    def __init__(self) -> None:
        self._positions: dict[str, dict[str, Position]] = {}
        self._lock = threading.Lock()

    def get_positions(self, portfolio: str = "default") -> dict[str, Position]:
        with self._lock:
            return dict(self._positions.get(portfolio, {}))

    def save_position(self, position: Position) -> None:
        with self._lock:
            bucket = self._positions.setdefault(position.portfolio, {})
            bucket[position.instrument] = position

    def save_positions(self, positions: list[Position]) -> None:
        with self._lock:
            for pos in positions:
                bucket = self._positions.setdefault(pos.portfolio, {})
                bucket[pos.instrument] = pos

    def delete_position(self, instrument: str, portfolio: str = "default") -> None:
        with self._lock:
            bucket = self._positions.get(portfolio)
            if bucket:
                bucket.pop(instrument, None)


class InMemoryBreachStore:
    """Thread-safe in-memory breach store."""

    def __init__(self) -> None:
        self._breaches: list[BreachRecord] = []
        self._lock = threading.Lock()

    def save_breach(self, breach: BreachRecord) -> None:
        with self._lock:
            self._breaches.append(breach)

    def save_breaches(self, breaches: list[BreachRecord]) -> None:
        with self._lock:
            self._breaches.extend(breaches)

    def get_breaches(
        self, *, limit: int = 100, **filters: Any
    ) -> list[BreachRecord]:
        with self._lock:
            result = list(self._breaches)

        # Apply filters
        if "severity" in filters:
            result = [b for b in result if b.severity == filters["severity"]]
        if "instrument" in filters:
            result = [b for b in result if b.instrument == filters["instrument"]]
        if "order_id" in filters:
            result = [b for b in result if b.order_id == filters["order_id"]]

        return result[-limit:]
