import os
from supabase import create_client, Client

SUPABASE_URL = os.environ.get("SUPABASE_URL", "")
SUPABASE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "")
SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "")

# Load from secrets if not in environment
if not SUPABASE_URL or not SUPABASE_KEY or not SUPABASE_ANON_KEY:
    try:
        from pathlib import Path
        BASE_DIR = Path(__file__).parent.parent
        with open(BASE_DIR / "config" / "secrets.env", "r") as f:
            for line in f:
                if line.startswith("SUPABASE_URL="):
                    SUPABASE_URL = line.split("=", 1)[1].strip().strip('"\'')
                elif line.startswith("SUPABASE_SERVICE_ROLE_KEY="):
                    SUPABASE_KEY = line.split("=", 1)[1].strip().strip('"\'')
                elif line.startswith("SUPABASE_ANON_KEY="):
                    SUPABASE_ANON_KEY = line.split("=", 1)[1].strip().strip('"\'')
    except Exception:
        pass

def get_supabase_client() -> Client | None:
    if not SUPABASE_URL or not SUPABASE_KEY:
        print("[Supabase] Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY. Operating in degraded mode.")
        return None
    return create_client(SUPABASE_URL, SUPABASE_KEY)

def provision_tenant(client: Client, business_name: str, subdomain: str, telnyx_assistant_id: str, html_payload: str) -> str | None:
    """
    Creates a new tenant row in the Supabase `tenants` table.
    Returns the newly created tenant UUID.
    """
    try:
        response = client.table("tenants").insert({
            "business_name": business_name,
            "subdomain": subdomain,
            "telnyx_assistant_id": telnyx_assistant_id,
            "html_payload": html_payload
        }).execute()
        
        if response.data and len(response.data) > 0:
            return response.data[0].get("id")
        return None
    except Exception as e:
        print(f"[Supabase] Failed to provision tenant for {business_name}: {e}")
        return None
