from __future__ import annotations

import os
import sys
import json
from typing import Any


def _load_env() -> None:
    try:
        from dotenv import load_dotenv  # type: ignore
        # Load standard .env and dev.env without overriding existing env
        load_dotenv(override=False)
        load_dotenv(dotenv_path="dev.env", override=False)
    except Exception:
        pass


def _mask(value: str | None, show_end: int = 4) -> str:
    if not value:
        return ""
    if len(value) <= show_end:
        return "*" * len(value)
    return "*" * (len(value) - show_end) + value[-show_end:]


def main() -> int:
    _load_env()

    project_url = os.getenv("SUPABASE_PROJECT_URL")
    service_key = os.getenv("SUPABASE_SERVICE_ROLE_API_KEY")
    client_id = os.getenv("SUPABASE_CLIENT_ID")

    print("Supabase ping - environment check:")
    print("  SUPABASE_PROJECT_URL:", bool(project_url))
    print("  SUPABASE_SERVICE_ROLE_API_KEY:", bool(service_key), _mask(service_key))
    print("  SUPABASE_CLIENT_ID:", bool(client_id), client_id)

    try:
        from supabase import create_client  # type: ignore
    except Exception as exc:  # pragma: no cover
        print("ERROR: Python package 'supabase' is not installed in this environment.")
        print("Install it with: pip install supabase")
        print("Exception:", repr(exc))
        return 2

    if not project_url or not service_key:
        print("ERROR: Missing SUPABASE_PROJECT_URL or SUPABASE_SERVICE_ROLE_API_KEY.")
        return 2

    try:
        client = create_client(supabase_url=project_url, supabase_key=service_key)  # type: ignore[arg-type]
        print("Client created ok.")
    except Exception as exc:
        print("ERROR: Failed to create Supabase client:", repr(exc))
        return 3

    # Try a lightweight select on messages
    try:
        resp: Any = client.table("messages").select("id", count="exact").limit(1).execute()
        # supabase-py v2 returns dict-like data; print compact summary
        data = getattr(resp, "data", None) or resp
        count = getattr(resp, "count", None) if hasattr(resp, "count") else None
        print("Query ok. Sample:", json.dumps(data[:1] if isinstance(data, list) else data, ensure_ascii=False))
        print("Total count (may be None if disabled):", count)
    except Exception as exc:
        print("WARN: Query to 'messages' failed. Table may not exist or permissions denied.")
        print("Exception:", repr(exc))
        # Still consider ping successful if we reached the API
        return 0

    return 0


if __name__ == "__main__":
    sys.exit(main())
