"""Internal /v1 introspection routes."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from ...models.v1.schema import Relationship, TableDescribeResponse, TableInfo

if TYPE_CHECKING:
    from ..._http import HttpTransport


class SchemaResource:
    """client.schema — tables, describe, relationships."""

    def __init__(self, http: HttpTransport) -> None:
        self._http = http

    def tables(self, schema_name: str | None = None) -> list[TableInfo]:
        params: dict[str, Any] = {}
        if schema_name is not None:
            params["schema_name"] = schema_name
        data = self._http.get("/introspection/tables", params=params)
        items = data.get("data", data) if isinstance(data, dict) else data
        if isinstance(items, list):
            return [TableInfo.model_validate(i) for i in items]
        return (
            [TableInfo.model_validate(i) for i in items.get("data", [])]
            if isinstance(items, dict)
            else []
        )

    def describe(self, schema_name: str, table_name: str) -> TableDescribeResponse:
        data = self._http.get(f"/introspection/tables/{schema_name}/{table_name}")
        payload = data.get("data", data) if isinstance(data, dict) else data
        return TableDescribeResponse.model_validate(payload)

    def relationships(self) -> list[Relationship]:
        data = self._http.get("/introspection/relationships")
        items = data.get("data", data) if isinstance(data, dict) else data
        if isinstance(items, list):
            return [Relationship.model_validate(i) for i in items]
        return []
