#!/usr/bin/env python3
# =============================================================================
# call-studio-api.py
#
# Call the Tableau External Client API on a running Tableau Studio instance.
# Discovers baseUrl + bearer token from the local <pid>.json file,
# checks /v0/health, then issues your request.
#
# This is the direct-call route to driving Tableau Studio headlessly. The other
# route is Tableau MCP, which puts an agent in front of the same API.
#
# Prerequisites
#   - Tableau Studio is running
#   - Python 3.9 or later
#
# How to use
#   python call-studio-api.py <METHOD> <path> [json-body] [options]
#
#   METHOD     HTTP method: GET, POST, PUT, PATCH, DELETE, …
#   path       Simplified API path. Leading slash optional.
#              Examples: v0/workbook   or   /v0/workbook
#   json-body  Optional JSON string for write methods (POST/PUT/PATCH)
#
#   --workbook NAME|PATH   Use the instance with this workbook open
#
# Examples
#   python call-studio-api.py GET v0/health
#   python call-studio-api.py GET v0/workbook
#   python call-studio-api.py GET v0/workbook --workbook lab.twb
#   python call-studio-api.py GET v0/workbook --workbook ~/books/lab.twb
#   python call-studio-api.py GET v0/site/workbooks        # waits for the result
#   python call-studio-api.py GET v0/operations/op_abc123
#   python call-studio-api.py POST v0/workbook:goToSheet \
#       '{"id":"{9BBEEE50-4AF9-46C2-BB36-1DAC6793FE4B}"}'
#
#   goToSheet takes a sheet id, not a name. Run GET v0/workbook first: every
#   entry under worksheets, dashboards, and storyboards carries the id.
#
# Output
#   The response body goes to stdout. Status lines, prompts, and errors go to
#   stderr, so `python call-studio-api.py GET v0/health | jq .status` works.
#
# Exit codes
#   0  the instance answered with a 2xx (after polling, the operation SUCCEEDED)
#   1  Tableau Studio not running or unreachable, the instance prompt was
#      cancelled or unanswered, or an operation outlived its timeout
#   2  bad usage — missing or malformed arguments, or a body that is not JSON
#   3  the instance answered with an error status, or the operation failed
#
# Discovery locations (written by Tableau Studio when the API starts)
#   macOS:   ~/Library/Application Support/Tableau/Tableau/ExternalApi/<pid>.json
#   Windows: %LOCALAPPDATA%\Tableau\Tableau\ExternalApi\<pid>.json
#
# Multiple Studio windows
#   With one window open, that window is used. With several, the script lists
#   them and asks which to use:
#
#     Multiple Tableau Studio instances are open. Choose one:
#       1) lab.twb (/Users/me/books/lab.twb)
#       2) sales.twb (/Users/me/books/2026/sales.twb)
#       3) Book1 (unsaved)
#
#   --workbook narrows that list without a prompt. It accepts either a name or
#   a path, matched case-insensitively against whole values, never substrings:
#
#     --workbook lab.twb                 file name
#     --workbook Book1                   in-app title (any workbook has one)
#     --workbook ~/books/lab.twb         path, with ~ expanded
#     --workbook ../books/lab.twb        path relative to the current directory
#
#   A workbook that has never been saved has no file name and no path, so its
#   title is the only thing left to name it by.
#
#   Anything holding a path separator or a leading ~ is resolved to an absolute,
#   symlink-free path before comparison, so any spelling of the same file works.
#   Resolution does not require the file to still exist on disk.
#
#   One match is used. Several matches are offered as a shorter prompt. A name
#   that matches nothing says so and then prompts over everything that is open,
#   so a typo costs you a keystroke rather than the run — but the script never
#   substitutes a different workbook on its own, because these calls can modify
#   whatever they land on. A workbook name is the only selector, and it is
#   deliberately the stable one: it keeps working across restarts of Tableau
#   Studio, which a process id would not.
#
#   --workbook selects among workbooks that are already open. It cannot open a
#   file: the discovery files only describe running instances.
#
# Note: some routes (e.g. GET v0/site/workbooks) return HTTP 202 with an
# operation id. Those are followed to completion for you, for up to
# POLL_TIMEOUT seconds. Fetch GET v0/operations/<id> yourself if you would
# rather track a long one by hand.
#
# Side effects / workspace impact
#   This script does NOT set environment variables, write files, install
#   packages, or modify your project workspace. It only:
#     - reads the local discovery <pid>.json (if present)
#     - sends HTTP requests to Tableau Studio on 127.0.0.1
#     - may read a choice from stdin when multiple instances are open
#     - prints the response to stdout
#   The bearer token only ever goes to a loopback address: a discovery file
#   pointing anywhere else is ignored, and redirects are refused rather than
#   followed, because urllib carries the Authorization header to the redirect
#   target even when that target is a different host.
#   Mutating API methods you supply (POST/PUT/PATCH/DELETE) can change the
#   open workbook in Tableau Studio — that is intentional and driven by your
#   arguments, not by this script itself.
# =============================================================================

from __future__ import annotations

import argparse
import ipaddress
import json
import os
import socket
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

EXIT_OK = 0
EXIT_UNREACHABLE = 1
EXIT_USAGE = 2
EXIT_HTTP_ERROR = 3

REQUEST_TIMEOUT = 30  # seconds, for the request you asked for
PROBE_TIMEOUT = 5  # seconds, for health checks and poll ticks, which run per instance
POLL_TIMEOUT = 30  # seconds to follow a long-running operation before giving up
POLL_INTERVAL = 0.25

TERMINAL_STATES = frozenset({"SUCCEEDED", "FAILED", "ERROR", "CANCELED", "CANCELLED"})

# Status codes worth explaining. Anything else prints the API's own error body,
# which is more specific than a guess would be.
HTTP_HINTS = {
    401: (
        "The session token was rejected. Tableau Studio issues a new one each "
        "launch, so a token copied from an earlier session will not work."
    ),
    403: "The Tableau External Client API refused this request.",
    404: (
        "No route at that path. Check it against the Tableau External Client "
        "API reference, and remember paths start with a version, e.g. v0/."
    ),
    405: "That path exists but does not accept this HTTP method.",
    409: "Tableau Studio could not apply this request in its current state.",
}


class NotLoopbackError(Exception):
    """Raised when a discovery file points somewhere other than this machine."""


class OperationTimeout(Exception):
    """Raised when a long-running operation outlives POLL_TIMEOUT.

    Distinct from a socket timeout: the request succeeded and the operation is
    still running inside Tableau Studio, so the caller can report the id rather
    than implying the call failed.
    """

    def __init__(self, op_id: str, waited: float):
        super().__init__(f"operation {op_id} did not finish within {waited:g}s")
        self.op_id = op_id
        self.waited = waited


# Failures that mean "no usable answer from this instance" rather than a bug.
# HTTPError subclasses URLError, so catch it first where the two differ.
REQUEST_ERRORS = (urllib.error.URLError, TimeoutError, NotLoopbackError)
PROBE_ERRORS = REQUEST_ERRORS + (KeyError,)  # discovery dict may lack baseUrl/token


class NoRedirectHandler(urllib.request.HTTPRedirectHandler):
    """Refuse redirects so the Authorization header cannot leave the instance.

    urllib's default handler strips only content-length and content-type when
    it follows a redirect, so a 302 would forward the bearer token to whatever
    host the response names. Returning None here lets the redirect fall through
    to the default error handler, surfacing it as an HTTPError instead.
    """

    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


_OPENER = urllib.request.build_opener(NoRedirectHandler)


def is_loopback(url: str) -> bool:
    """Return True if url is plain HTTP addressed to this machine."""
    parsed = urllib.parse.urlparse(url)
    if parsed.scheme != "http":
        return False
    host = parsed.hostname
    if host is None:
        return False
    if host == "localhost":
        return True
    try:
        return ipaddress.ip_address(host).is_loopback
    except ValueError:
        return False


def discovery_dirs() -> list[Path]:
    """Return candidate folders where Studio publishes <pid>.json discovery files.

    Studio writes to Qt's AppLocalDataLocation, which uses a doubled
    Tableau/Tableau segment. A single-segment path is included as a fallback
    for builds that collapse the org name. Override is not supported here —
    this helper only reads standard OS locations and never writes.
    """
    if sys.platform == "win32":
        # e.g. C:\Users\<user>\AppData\Local
        root = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
    elif sys.platform == "darwin":
        # e.g. ~/Library/Application Support
        root = Path.home() / "Library" / "Application Support"
    else:
        # Linux / other: XDG data home
        root = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
    return [
        root / "Tableau" / "Tableau" / "ExternalApi",  # primary (live-confirmed)
        root / "Tableau" / "ExternalApi",  # fallback
    ]


def pid_alive(pid: int) -> bool:
    """Return True if the OS process id from a discovery file is still running.

    Used to ignore stale <pid>.json files left behind after Studio exits.
    Does not terminate or signal the process beyond a non-destructive check.
    """
    if pid <= 0:
        return False
    if sys.platform == "win32":
        import ctypes

        # OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION) succeeds only if alive.
        kernel32 = ctypes.windll.kernel32
        kernel32.OpenProcess.restype = ctypes.c_void_p
        handle = kernel32.OpenProcess(0x1000, False, pid)
        if handle:
            kernel32.CloseHandle(ctypes.c_void_p(handle))
            return True
        return False
    try:
        os.kill(pid, 0)  # signal 0: existence check only; does not kill
    except ProcessLookupError:
        return False
    except PermissionError:
        return True  # exists, just owned by another user
    except OSError:
        return False
    return True


def scan_discovery() -> dict:
    """Read every discovery file and sort it into live, stale, or unusable.

    Scans discovery_dirs() for schemaVersion == 1 JSON files. The first
    directory wins when a pid appears in both. Read-only: never creates,
    updates, or deletes discovery files.

    Returns a dict with:
        live        parsed dicts (baseUrl + token) for instances still running
        stale       pids whose discovery file outlived the process
        unreadable  file names that were not usable schemaVersion 1 JSON
        remote      file names whose baseUrl was not a loopback address
        searched    directories that existed and were scanned

    Everything except live is kept so that a failure can say which of several
    quite different situations actually occurred.
    """
    found: dict = {
        "live": [],
        "stale": [],
        "unreadable": [],
        "remote": [],
        "searched": [],
    }
    by_pid: dict[int, dict] = {}
    for directory in discovery_dirs():
        if not directory.is_dir():
            continue
        found["searched"].append(directory)
        for path in sorted(directory.glob("*.json")):
            try:
                data = json.loads(path.read_text(encoding="utf-8"))
            except (OSError, json.JSONDecodeError):
                found["unreadable"].append(path.name)
                continue
            if not isinstance(data, dict) or data.get("schemaVersion") != 1:
                found["unreadable"].append(path.name)
                continue
            try:
                pid = int(data.get("pid", -1))
            except (TypeError, ValueError):
                found["unreadable"].append(path.name)
                continue
            if not pid_alive(pid):
                found["stale"].append(pid)  # left behind after Studio quit
                continue
            base = data.get("baseUrl")
            if not isinstance(base, str) or not is_loopback(base):
                found["remote"].append(path.name)
                continue
            by_pid.setdefault(pid, data)
    found["live"] = list(by_pid.values())
    return found


def report_missing_studio(found: dict) -> None:
    """Say why no instance was found, as specifically as the evidence allows."""
    print("Tableau Studio does not appear to be running.", file=sys.stderr)
    if not found["searched"]:
        print(
            "  No discovery folder exists yet. Tableau Studio creates one the "
            "first time it starts.",
            file=sys.stderr,
        )
    elif found["stale"]:
        pids = ", ".join(str(p) for p in sorted(set(found["stale"])))
        print(
            f"  Found discovery files from an earlier session (pid {pids}), but "
            "those processes have exited.",
            file=sys.stderr,
        )
    for directory in found["searched"] or discovery_dirs():
        print(f"  Looked in: {directory}", file=sys.stderr)
    print("  Open Tableau Studio, then run this again.", file=sys.stderr)


def report_unhealthy(live: list[dict]) -> None:
    """Explain that Studio is up but its API is not answering yet."""
    pids = ", ".join(str(inst.get("pid", "?")) for inst in live)
    print(
        f"Tableau Studio is running (pid {pids}), but the Tableau External "
        "Client API did not answer GET /v0/health.",
        file=sys.stderr,
    )
    print(
        "  The API becomes available only once Tableau Studio has fully "
        "started. Wait a moment, then run this again.",
        file=sys.stderr,
    )


def warn_about_unusable(found: dict) -> None:
    """Mention discovery files that were skipped, without failing the run.

    These are advisory: a healthy instance may well exist alongside them, so
    the run continues. The remote case is the security-relevant one — the
    bearer token is never sent off this machine.
    """
    for name in found["unreadable"]:
        print(
            f"Ignoring {name}: not a readable Tableau External Client API "
            "discovery file.",
            file=sys.stderr,
        )
    for name in found["remote"]:
        print(
            f"Ignoring {name}: its baseUrl is not on this machine, so the "
            "session token will not be sent to it.",
            file=sys.stderr,
        )


def parse_body(raw: str) -> object:
    """Parse a response body as JSON, falling back to the raw text."""
    if not raw:
        return None
    try:
        return json.loads(raw)
    except json.JSONDecodeError:
        return raw


def format_payload(payload: object) -> str:
    """Render a parsed body for printing: JSON indented, text as-is."""
    if payload is None:
        return ""
    if isinstance(payload, str):
        return payload
    return json.dumps(payload, indent=2)


def api_request(
    base: str,
    token: str,
    method: str,
    path: str,
    body: bytes | None = None,
    timeout: float = REQUEST_TIMEOUT,
) -> tuple[int, object]:
    """Send one authenticated request to the loopback Tableau External Client API.

    Args:
        base:    Loopback root from discovery, e.g. http://127.0.0.1:50421
        token:   Per-session bearer token from discovery
        method:  HTTP verb (case-insensitive)
        path:    API path; leading slash optional (v0/workbook or /v0/workbook)
        body:    Optional raw JSON bytes for write methods
        timeout: Socket timeout in seconds

    Returns:
        (http_status, parsed_json_or_text_or_None)

    Raises:
        NotLoopbackError if base does not address this machine.
        urllib.error.HTTPError / URLError on transport or HTTP failure.
    """
    if not path.startswith("/"):
        path = "/" + path  # normalize simplified URIs from the CLI
    url = base.rstrip("/") + path
    if not is_loopback(url):
        raise NotLoopbackError(f"Refusing to send the bearer token to {base}")
    req = urllib.request.Request(
        url,
        data=body,
        headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},
        method=method.upper(),
    )
    if body is not None:
        req.add_header("Content-Type", "application/json")
    with _OPENER.open(req, timeout=timeout) as resp:
        return resp.status, parse_body(resp.read().decode(errors="replace"))


def is_healthy(inst: dict) -> bool:
    """Return True if this instance answers GET /v0/health with status OK."""
    try:
        status, health = api_request(
            inst["baseUrl"], inst["token"], "GET", "/v0/health", timeout=PROBE_TIMEOUT
        )
    except PROBE_ERRORS:
        return False
    return status == 200 and isinstance(health, dict) and health.get("status") == "OK"


def clean_str(value: object) -> str | None:
    """Return a stripped non-empty string, or None for anything else."""
    if isinstance(value, str) and value.strip():
        return value.strip()
    return None


def workbook_identity(inst: dict) -> tuple[str | None, str | None]:
    """Return (title, location) for the workbook open in this instance.

    Both are None when the instance does not answer GET /v0/workbook, which is
    treated as "unidentifiable" rather than an error: the instance is still
    usable, it just cannot be named or matched.
    """
    try:
        _, wb = api_request(
            inst["baseUrl"], inst["token"], "GET", "/v0/workbook", timeout=PROBE_TIMEOUT
        )
    except PROBE_ERRORS:
        return None, None
    if not isinstance(wb, dict):
        return None, None
    return clean_str(wb.get("title")), clean_str(wb.get("location"))


def instance_label(inst: dict, title: str | None, location: str | None) -> str:
    """Render one chooser line: workbook name followed by where it lives.

    Saved workbooks read as "lab.twb (/Users/me/books/lab.twb)", so two windows
    on same-named files in different folders stay distinguishable. Workbooks
    with no file on disk read as "Book1 (unsaved)".
    """
    if location:
        return f"{Path(location).name} ({location})"
    if title:
        return f"{title} (unsaved)"
    return f"pid {inst.get('pid', '?')} @ {inst.get('baseUrl', '?')}"


def looks_like_path(value: str) -> bool:
    """Return True if value is written like a path rather than a bare name.

    Backslash only counts on Windows, where it is a separator; elsewhere it is
    a legal character in a file name.
    """
    if value.startswith("~"):
        return True
    if "/" in value:
        return True
    return sys.platform == "win32" and "\\" in value


def resolve_path(value: str) -> str | None:
    """Return value as an absolute, symlink-free path, or None if unresolvable.

    Expands ~ and resolves relative segments against the current directory, so
    ~/books/lab.twb, ../books/lab.twb, and /Users/me/books/lab.twb all reduce
    to one comparable string. Existence is not required: a workbook moved or
    deleted since Tableau Studio opened it should still be selectable.
    """
    try:
        return str(Path(value).expanduser().resolve())
    except (OSError, RuntimeError, ValueError):
        return None


def workbook_matches(wanted: str, title: str | None, location: str | None) -> bool:
    """Return True if wanted identifies this workbook, by name or by path.

    Compares case-insensitively against the three things a person might
    reasonably type — the file name, the file's path, and the in-app title —
    and requires the whole value to match. Substring matching is deliberately
    left out: it would make a path ambiguous with the shorter names inside it,
    which is the opposite of why someone would type a path.

    Path comparison happens on resolved paths, so a relative or ~-prefixed
    spelling matches the absolute location that Tableau Studio reports.
    """
    wanted = wanted.strip()
    if not wanted:
        return False
    folded = wanted.casefold()

    if title and title.casefold() == folded:
        return True
    if not location:
        return False
    if location.casefold() == folded or Path(location).name.casefold() == folded:
        return True

    if looks_like_path(wanted):
        target, actual = resolve_path(wanted), resolve_path(location)
        return bool(target and actual and target.casefold() == actual.casefold())
    return False


def describe_instances(instances: list[dict]) -> list[dict]:
    """Pair each instance with its workbook title, location, and chooser label.

    Costs one GET /v0/workbook per instance, so callers should only reach for
    this when they actually need to name instances — not on the common path
    where a single window is open and no selection is required.
    """
    described = []
    for inst in instances:
        title, location = workbook_identity(inst)
        described.append(
            {
                "inst": inst,
                "title": title,
                "location": location,
                "label": instance_label(inst, title, location),
            }
        )
    return described


def prompt_for_instance(described: list[dict], heading: str) -> dict | None:
    """List the candidates and read a choice from stdin.

    Everything here goes to stderr so stdout stays clean for the response body.
    Returns the chosen discovery dict, or None if the input is unusable — which
    includes EOF, so a non-interactive caller gets the listing and a clean exit
    instead of hanging on a prompt nobody will answer.
    """
    print(heading, file=sys.stderr)
    for i, described_inst in enumerate(described, start=1):
        print(f"  {i}) {described_inst['label']}", file=sys.stderr)

    print(f"Enter 1-{len(described)}: ", end="", file=sys.stderr, flush=True)
    try:
        choice = int(input().strip())
    except (EOFError, ValueError):
        print(
            "\nInvalid choice. Use --workbook to choose without a prompt.",
            file=sys.stderr,
        )
        return None

    if choice < 1 or choice > len(described):
        print("Invalid choice.", file=sys.stderr)
        return None
    return described[choice - 1]["inst"]


def choose_instance(instances: list[dict], workbook: str | None = None) -> dict | None:
    """Pick one healthy instance, prompting whenever the choice is not settled.

    A workbook name narrows the candidates: one match is used, several are
    offered as a shorter prompt, and none falls back to a prompt over
    everything that is open, prefaced by the fact that the name did not match.
    The script never silently substitutes a different workbook, since these
    calls can modify whatever they land on — but a typo is recoverable rather
    than fatal. With no selector, a lone instance is used and anything more
    prompts.

    Returns the chosen discovery dict, or None if the user cancelled or the
    prompt had no one to answer it.
    """
    if workbook is not None:
        described = describe_instances(instances)
        matches = [
            d for d in described if workbook_matches(workbook, d["title"], d["location"])
        ]
        if not matches:
            print(
                f'No workbook open in Tableau Studio matches "{workbook}".',
                file=sys.stderr,
            )
            if looks_like_path(workbook):
                print(
                    f"  Compared as the path: {resolve_path(workbook)}",
                    file=sys.stderr,
                )
            return prompt_for_instance(
                described, "Choose from the workbooks that are open:"
            )
        if len(matches) == 1:
            return matches[0]["inst"]
        return prompt_for_instance(
            matches, f'More than one open workbook matches "{workbook}". Choose one:'
        )

    if len(instances) == 1:
        return instances[0]

    return prompt_for_instance(
        describe_instances(instances),
        "Multiple Tableau Studio instances are open. Choose one:",
    )


def operation_id(status: int, payload: object) -> str | None:
    """Return the operation id if this response deferred the work to an Operation.

    HTTP 202 is the contract for a deferred route, so it is required alongside
    the payload shape. Shape alone would misread an ordinary resource that
    happens to carry both id and state, sending the caller to an operations URL
    that does not exist; it would also make a direct GET of
    /v0/operations/<id> block until terminal instead of answering with the
    snapshot the caller asked for, since that route replies 200.
    """
    if status != 202:
        return None
    if isinstance(payload, dict) and isinstance(payload.get("id"), str):
        if "state" in payload:
            return payload["id"]
    return None


def poll_operation(
    base: str, token: str, op_id: str, timeout: float = POLL_TIMEOUT
) -> tuple[int, object]:
    """Poll GET /v0/operations/<id> until the operation reaches a terminal state.

    Raises OperationTimeout if timeout seconds pass first; HTTP and transport
    failures propagate to the caller like any other request. The deadline is
    checked after each tick, so one poll always happens even at timeout 0.
    """
    deadline = time.monotonic() + timeout
    while True:
        status, payload = api_request(
            base, token, "GET", f"/v0/operations/{op_id}", timeout=PROBE_TIMEOUT
        )
        if isinstance(payload, dict) and payload.get("state") in TERMINAL_STATES:
            return status, payload
        if time.monotonic() >= deadline:
            raise OperationTimeout(op_id, timeout)
        time.sleep(POLL_INTERVAL)


def describe_request_error(err: Exception) -> str:
    """Turn a transport failure into a line that says what to do about it."""
    if isinstance(err, NotLoopbackError):
        return str(err)
    # URLError wraps the real cause; bare socket errors are their own cause.
    reason = getattr(err, "reason", err)
    if isinstance(reason, (TimeoutError, socket.timeout)):
        return (
            f"Tableau Studio did not answer within {REQUEST_TIMEOUT} seconds. "
            "It may be busy with a dialog or a long redraw."
        )
    if isinstance(reason, ConnectionRefusedError):
        return (
            "Tableau Studio is no longer listening on the discovered port. "
            "The window was probably closed — run this again to rediscover it."
        )
    return f"Could not reach the Tableau External Client API: {reason}"


def report_http_error(err: urllib.error.HTTPError) -> None:
    """Print an API error status, any hint we have for it, and its body."""
    print(f"HTTP {err.code} from the Tableau External Client API", file=sys.stderr)
    if 300 <= err.code < 400:
        print(
            "  Redirects are refused so the session token cannot follow one to "
            "another host.",
            file=sys.stderr,
        )
    elif err.code in HTTP_HINTS:
        print(f"  {HTTP_HINTS[err.code]}", file=sys.stderr)

    body = format_payload(parse_body(err.read().decode(errors="replace")))
    if body:
        print(body)


def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        prog="call-studio-api.py",
        description=(
            "Call the Tableau External Client API on a running Tableau Studio "
            "instance."
        ),
        epilog="Example: python call-studio-api.py GET v0/workbook",
    )
    parser.add_argument("method", metavar="METHOD", help="HTTP method, e.g. GET or POST")
    parser.add_argument(
        "path", metavar="PATH", help="API path; leading slash optional, e.g. v0/workbook"
    )
    parser.add_argument(
        "body",
        metavar="JSON-BODY",
        nargs="?",
        help="JSON string for write methods (POST/PUT/PATCH)",
    )
    parser.add_argument(
        "--workbook",
        metavar="NAME|PATH",
        help=(
            "target the instance with this workbook open; accepts the file name, "
            "a path to the file (~ and relative paths are resolved), or the "
            "in-app title"
        ),
    )
    return parser.parse_args(argv)


def main(argv: list[str] | None = None) -> int:
    """CLI entry: parse args, discover Studio, health-check, then call the API.

    Exit codes:
        0 — the instance answered with a 2xx (after polling, operation SUCCEEDED)
        1 — Tableau Studio not running or unreachable, the instance prompt was
            cancelled or unanswered, or an operation timed out
        2 — bad usage (malformed arguments, or a body that is not valid JSON)
        3 — the instance answered with an error status, or the operation failed
    """
    args = parse_args(argv)

    # --- catch argument mistakes before touching Tableau Studio ---
    if not args.method.isalpha():
        print(f'"{args.method}" is not an HTTP method.', file=sys.stderr)
        print(
            "  Usage: python call-studio-api.py <METHOD> <path> [json-body]",
            file=sys.stderr,
        )
        return EXIT_USAGE
    if args.workbook is not None and not args.workbook.strip():
        print("--workbook needs a workbook name or path.", file=sys.stderr)
        return EXIT_USAGE

    # --- validate the body here so a malformed one never reaches a write route ---
    body = None
    if args.body is not None:
        try:
            json.loads(args.body)
        except json.JSONDecodeError as e:
            print(f"Body is not valid JSON: {e}", file=sys.stderr)
            return EXIT_USAGE
        if args.method.upper() in ("GET", "HEAD"):
            print(
                f"Warning: sending a body with {args.method.upper()}, which the "
                "Tableau External Client API is unlikely to read.",
                file=sys.stderr,
            )
        body = args.body.encode()

    # --- discover live Studio instances (baseUrl + bearer token) ---
    found = scan_discovery()
    warn_about_unusable(found)
    if not found["live"]:
        report_missing_studio(found)
        return EXIT_UNREACHABLE

    healthy = [inst for inst in found["live"] if is_healthy(inst)]
    if not healthy:
        report_unhealthy(found["live"])
        return EXIT_UNREACHABLE

    # --- narrow to one window, prompting only if the choice is still ambiguous ---
    inst = choose_instance(healthy, args.workbook)
    if not inst:
        return EXIT_UNREACHABLE

    base, token = inst["baseUrl"], inst["token"]

    # --- caller-supplied request, followed to completion if it defers work ---
    polled = False
    try:
        status, payload = api_request(base, token, args.method, args.path, body)
        op_id = operation_id(status, payload)
        polled = op_id is not None
        if op_id:
            print(f"HTTP {status} — waiting for operation {op_id}", file=sys.stderr)
            status, payload = poll_operation(base, token, op_id)
    except OperationTimeout as e:
        # The call worked; only our patience ran out, so say where to look next.
        print(
            f"Timed out after {e.waited:g}s waiting for operation {e.op_id}.",
            file=sys.stderr,
        )
        print(
            "  It is still running in Tableau Studio. Check on it with:",
            file=sys.stderr,
        )
        print(
            f"    python call-studio-api.py GET v0/operations/{e.op_id}",
            file=sys.stderr,
        )
        return EXIT_UNREACHABLE
    except urllib.error.HTTPError as e:
        # Surface API error bodies (JSON when possible) instead of a traceback
        report_http_error(e)
        return EXIT_HTTP_ERROR
    except REQUEST_ERRORS as e:
        print(describe_request_error(e), file=sys.stderr)
        return EXIT_UNREACHABLE

    # --- print result: body on stdout, everything else on stderr ---
    print(f"HTTP {status}", file=sys.stderr)
    output = format_payload(payload)
    if output:
        print(output)

    if polled and isinstance(payload, dict):
        state = payload.get("state")
        if state in TERMINAL_STATES and state != "SUCCEEDED":
            print(f"Operation ended in state {state}.", file=sys.stderr)
            return EXIT_HTTP_ERROR
    return EXIT_OK if status < 400 else EXIT_HTTP_ERROR


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except KeyboardInterrupt:
        # Ctrl-C at the instance prompt is a normal way to back out, not a crash.
        print("\nCancelled.", file=sys.stderr)
        raise SystemExit(EXIT_UNREACHABLE)
