# app/src/storage/repositories/balance_snapshots.py

from __future__ import annotations

import json
from typing import Any

from src.storage.session import get_connection


class BalanceSnapshotRepository:
    def add_snapshot(
        self,
        *,
        source: str,
        payload: dict[str, Any],
    ) -> None:
        payload_json = json.dumps(payload, ensure_ascii=False)

        with get_connection() as connection:
            with connection.cursor() as cursor:
                cursor.execute(
                    '''
                    INSERT INTO balance_snapshots (source, payload_json)
                    VALUES (%s, %s::jsonb)
                    ''',
                    (source, payload_json),
                )

    def count_snapshots(self) -> int:
        with get_connection() as connection:
            with connection.cursor() as cursor:
                cursor.execute("SELECT COUNT(*) FROM balance_snapshots")
                row = cursor.fetchone()

        return int(row[0]) if row else 0

    def list_recent_snapshots(self, limit: int = 5) -> list[dict[str, str]]:
        with get_connection() as connection:
            with connection.cursor() as cursor:
                cursor.execute(
                    '''
                    SELECT created_at, source, payload_json::text
                    FROM balance_snapshots
                    ORDER BY created_at DESC, id DESC
                    LIMIT %s
                    ''',
                    (limit,),
                )
                rows = cursor.fetchall()

        items: list[dict[str, str]] = []
        for row in rows:
            items.append(
                {
                    "created_at": str(row[0]),
                    "source": str(row[1]),
                    "payload_json": str(row[2]),
                }
            )

        return items