"""
ZIA API — In-memory Run Store.

Stores RunRecord objects keyed by run_id.
Thread-safe for single-process use.

Phase 2: swap _store for a Redis/Postgres-backed implementation
using the same interface.
"""

from __future__ import annotations

import threading
from typing import Optional

from zia.api.models import RunRecord, RunStatus


class RunStore:
    """
    Singleton in-memory store for agent run records.
    Thread-safe via a simple RLock.
    """

    _instance: RunStore | None = None

    def __init__(self) -> None:
        self._store: dict[str, RunRecord] = {}
        self._lock = threading.RLock()

    @classmethod
    def get(cls) -> RunStore:
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    def create(self, record: RunRecord) -> RunRecord:
        with self._lock:
            self._store[record.run_id] = record
        return record

    def get_run(self, run_id: str) -> Optional[RunRecord]:
        with self._lock:
            return self._store.get(run_id)

    def update(self, record: RunRecord) -> RunRecord:
        with self._lock:
            self._store[record.run_id] = record
        return record

    def list_for_tenant(self, tenant_id: str) -> list[RunRecord]:
        with self._lock:
            return [r for r in self._store.values() if r.tenant_id == tenant_id]

    def all_runs(self) -> list[RunRecord]:
        with self._lock:
            return list(self._store.values())

    def clear(self) -> None:
        """For tests."""
        with self._lock:
            self._store.clear()
