"""Mercury Finance plugin — adapter that satisfies the FinanceProvider protocol.

Wraps MercuryClient from vastian.integrations.mercury. Satisfies FinanceProvider
via get_balances, list_accounts, get_transactions.

Protocol satisfaction: isinstance(MercuryFinanceAdapter(...), FinanceProvider) is True.
"""

from __future__ import annotations

from typing import Any

from vastian.bridges.protocols import FinanceProvider
from vastian.integrations.mercury import MercuryClient

__all__ = [
    "MercuryFinanceAdapter",
    "register",
    "format_balance",
    "format_transactions",
]


def _filter_by_date_range(
    items: list[dict[str, Any]],
    start_date: str | None,
    end_date: str | None,
    date_key: str = "postedAt",
) -> list[dict[str, Any]]:
    """Filter items by date range using postedAt or createdAt."""
    if not start_date and not end_date:
        return items
    result = []
    for item in items:
        raw = item.get(date_key) or item.get("createdAt") or ""
        if not raw:
            result.append(item)
            continue
        # ISO8601-like: "2024-01-15T12:00:00Z" -> compare first 10 chars
        date_str = str(raw)[:10]
        if start_date and date_str < start_date[:10]:
            continue
        if end_date and date_str > end_date[:10]:
            continue
        result.append(item)
    return result


class MercuryFinanceAdapter:
    """Adapter that wraps MercuryClient and satisfies the FinanceProvider protocol."""

    def __init__(
        self,
        api_token: str,
        default_account_id: str = "",
        readonly_account_ids: list[str] | None = None,
        account_names: dict[str, str] | None = None,
    ) -> None:
        self._client = MercuryClient(
            api_token=api_token,
            default_account_id=default_account_id,
            readonly_account_ids=readonly_account_ids,
            account_names=account_names,
        )

    async def get_balances(self) -> list[dict]:
        """Get balances for all configured accounts."""
        return await self._client.get_all_balances()

    async def list_accounts(self) -> list[dict]:
        """List all configured accounts with metadata."""
        return await self._client.get_accounts()

    async def get_transactions(
        self,
        account_id: str,
        start_date: str | None = None,
        end_date: str | None = None,
    ) -> list[dict]:
        """Get transactions for an account, optionally filtered by date."""
        txns = await self._client.list_transactions(account_id, limit=500)
        return _filter_by_date_range(txns, start_date, end_date)

    def format_balance(self, account: dict[str, Any]) -> str:
        """Human-readable balance summary (convenience delegate)."""
        return MercuryClient.format_balance(account)

    def format_all_balances(
        self,
        accounts: list[dict[str, Any]],
        primary_id: str = "",
    ) -> str:
        """Human-readable multi-account balance summary (convenience delegate)."""
        return self._client.format_all_balances(accounts, primary_id)

    def format_transactions(
        self,
        txns: list[dict[str, Any]],
        limit: int = 10,
    ) -> str:
        """Human-readable transaction list (convenience delegate)."""
        return MercuryClient.format_transactions(txns, limit)


# Module-level convenience exports
format_balance = MercuryClient.format_balance
format_all_balances = MercuryClient.format_all_balances
format_transactions = MercuryClient.format_transactions


def register() -> None:
    """Register the Mercury Finance plugin with the loader."""
    from vastian.loader import register as loader_register

    loader_register("mercury_finance", MercuryFinanceAdapter)


# Protocol satisfaction: isinstance(MercuryFinanceAdapter(...), FinanceProvider) is True
def _assert_protocol() -> None:
    adapter = MercuryFinanceAdapter(api_token="dummy")
    assert isinstance(adapter, FinanceProvider), (
        "MercuryFinanceAdapter must satisfy FinanceProvider"
    )


_assert_protocol()
