"""
Convexity SDK - Create Databricks Connections

This sample demonstrates how to:
- Look up an existing organization and project by slug
- Create Databricks connections using the generated API client
- Verify each connection after creation

Prerequisites:
- A valid API key with WRITE or ADMIN permission
- The "Convexity SDK samples" organization and "griffin it" project must
  already exist. Run `create_org_and_project.py` first if they don't.
- Set DATABRICKS_* environment variables in .env (see .env.example)
"""

import os
import sys

from convexity_sdk import ConvexityClient

ORG_SLUG = "convexity-sdk-samples"
PROJECT_SLUG = "griffin-it"

# ── Initialise SDK client ───────────────────────────────────────────────
client = ConvexityClient()

# ── Step 1: Resolve organization ────────────────────────────────────────
org = client.organizations.get_by_slug(ORG_SLUG)
if org is None or not hasattr(org, "id"):
    print(
        f'ERROR: Organization "{ORG_SLUG}" not found.\nPlease run create_org_and_project.py first.',
        file=sys.stderr,
    )
    raise SystemExit(1)
print(f"Found organization: {org.name} (id={org.id})")

# ── Step 2: Resolve project ────────────────────────────────────────────
project = client.projects.get_by_slug(org.id, PROJECT_SLUG)
if project is None or not hasattr(project, "id"):
    print(
        f'ERROR: Project "{PROJECT_SLUG}" not found in organization "{ORG_SLUG}".\nPlease run create_org_and_project.py first.',
        file=sys.stderr,
    )
    raise SystemExit(1)
print(f"Found project: {project.name} (id={project.id})")

# ── Step 3: Read Databricks credentials from environment ────────────────
server_hostname = os.environ["DATABRICKS_SERVER_HOSTNAME"]
http_path = os.environ["DATABRICKS_HTTP_PATH"]
access_token = os.environ["DATABRICKS_ACCESS_TOKEN"]

# ── Step 4: Create "canonical" Databricks connection ────────────────────
canonical = client.connections.create_databricks(
    name="canonical",
    project_id=project.id,
    server_hostname=server_hostname,
    http_path=http_path,
    access_token=access_token,
    db_schema="analytics",
    description="Databricks canonical connection (analytics schema)",
)
print(f"Created connection: {canonical.name} (id={canonical.id})")

# ── Step 5: Create "analytic" Databricks connection ─────────────────────
analytic = client.connections.create_databricks(
    name="analytic",
    project_id=project.id,
    server_hostname=server_hostname,
    http_path=http_path,
    access_token=access_token,
    db_schema="canonical",
    description="Databricks analytic connection (canonical schema)",
)
print(f"Created connection: {analytic.name} (id={analytic.id})")

# ── Step 6: Verify both connections ─────────────────────────────────────
for conn in [canonical, analytic]:
    result = client.connections.verify_databricks(conn.id)
    status = "OK" if result.success else "FAILED"
    print(f"  Verify [{conn.name}]: {status} — {result.message}")

print("\nDone!")

# -- Step 7: Print the schemas of both connections to verify they are different --
print(f"\nCanonical connection schema: {canonical.db_schema}")
print(f"Analytic connection schema: {analytic.db_schema}")
client.close()
