"""
aiel_sdk.integrations.postgres.remote
=====================================

Remote-backed Postgres operations via the AIEL Integrations API.
"""

from __future__ import annotations

from typing import Any, Dict, Optional

from ...client import AielClient
from .types import (
    DEFAULT_POSTGRES_CAPABILITIES,
    PostgresCapabilities,
    PostgresInsertRequest,
    PostgresInsertResult,
    PostgresQueryRequest,
    PostgresQueryResult,
)

Json = Dict[str, Any]


def _ensure_non_empty(value: str, name: str) -> str:
    v = (value or "").strip()
    if not v:
        raise ValueError(f"{name} must be non-empty")
    return v


class RemotePostgres:
    @property
    def capabilities(self) -> PostgresCapabilities:
        return DEFAULT_POSTGRES_CAPABILITIES

    def __init__(
        self,
        client: AielClient,
        *,
        workspace_id: str,
        project_id: str,
        connection_id: str,
    ) -> None:
        self._c = client
        self._ws = _ensure_non_empty(workspace_id, "workspace_id")
        self._proj = _ensure_non_empty(project_id, "project_id")
        self._conn = _ensure_non_empty(connection_id, "connection_id")

    def _invoke(
        self,
        *,
        action: str,
        params: Optional[Json] = None,
        request_id: str | None = None,
    ) -> Any:
        return self._c.integrations.invoke_action(
            self._ws,
            self._proj,
            connection_id=self._conn,
            action=action,
            payload={"params": params or {}},
            request_id=request_id,
        )

    def query(self, req: PostgresQueryRequest, *, request_id: str | None = None) -> PostgresQueryResult:
        raw = self._invoke(action="postgres.query", params=req.to_params(), request_id=request_id)
        return PostgresQueryResult.from_json(raw if isinstance(raw, dict) else {"raw": raw})

    def insert(self, req: PostgresInsertRequest, *, request_id: str | None = None) -> PostgresInsertResult:
        raw = self._invoke(action="postgres.insert", params=req.to_params(), request_id=request_id)
        return PostgresInsertResult.from_json(raw if isinstance(raw, dict) else {"raw": raw})
