"""
Convexity SDK - Share a Dashboard with a Public Link

This sample demonstrates how to:
- Look up the "Analytic Dashboard" created by create_dashboards.py
- Create a public shareable link for that dashboard
- Print the shareable URL that anyone can use to view the dashboard

Prerequisites:
- A valid API key with WRITE or ADMIN permission
- The "Convexity SDK samples" org, "griffin it" project, and
  "Analytic Dashboard" must already exist.
  Run the previous samples in order:
    1. create_org_and_project.py
    2. create_databricks_connections.py
    3. create_datasets.py
    4. create_dashboards.py
"""

import sys

from convexity_api_client.models.create_share_request import CreateShareRequest

from convexity_sdk import ConvexityClient

ORG_SLUG = "convexity-sdk-samples"
PROJECT_SLUG = "griffin-it"
DASHBOARD_NAME = "Analytic Dashboard"

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

# ── Step 1: Verify organization exists ──────────────────────────────────
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: Verify project exists ──────────────────────────────────────
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 org "{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: Find the dashboard ─────────────────────────────────────────
dashboards_resp = client.dashboards.list(project.id)
if dashboards_resp is None or not hasattr(dashboards_resp, "dashboards"):
    print("ERROR: Could not list dashboards.", file=sys.stderr)
    raise SystemExit(1)

dashboard = next(
    (d for d in dashboards_resp.dashboards if d.name == DASHBOARD_NAME),
    None,
)
if dashboard is None:
    print(
        f'ERROR: Dashboard "{DASHBOARD_NAME}" not found.\nPlease run create_dashboards.py first.',
        file=sys.stderr,
    )
    raise SystemExit(1)
print(f"Found dashboard: {dashboard.name} (id={dashboard.id})")

# ── Step 4: Create a public share link ─────────────────────────────────
print("\nCreating public share link …")

share_request = CreateShareRequest(
    allow_filtering=False,
    show_branding=True,
)

share = client.dashboards.create_share(
    dashboard_id=dashboard.id,
    body=share_request,
)
if share is None or not hasattr(share, "share_token"):
    print("ERROR: Failed to create share link.", file=sys.stderr)
    raise SystemExit(1)

# ── Step 5: Print the shareable URL ────────────────────────────────────
# The public URL format is: <frontend_origin>/share/<share_token>
# For local development the frontend typically runs on http://localhost:5173
share_url = f"{client.base_url.replace('/api', '').rstrip('/')}/share/{share.share_token}"

print(f"  Share ID    : {share.id}")
print(f"  Share token : {share.share_token}")
print(f"  Active      : {share.is_active}")
print(f"  Shareable URL: {share_url}")

print("\nAnyone with this URL can view the dashboard (no login required).")
print("Done!")
client.close()
