#!/usr/bin/env python3
"""
tsapi is a lightweight wrapper for calling the Tailscale API with
a local instance of the Tailscale control plane. It's to save me
remembering the exact set of curl commands I need.
"""

import argparse
import json
import shlex
import subprocess
from typing import TypedDict

from chives.text import coloured

Args = TypedDict(
    "args",
    {
        "method": str,
        "path": str,
        "api_key": str,
        "data": str,
    },
)


def parse_args():
    parser = argparse.ArgumentParser(
        prog="tsapi",
        description="Make API calls to a local instance of devcontrol",
    )

    parser.add_argument("--endpoint", help="API endpoint", required=True)
    parser.add_argument("--api-key", help="API key", required=True)
    parser.add_argument("--data", help="Body to POST with the request")

    args = parser.parse_args()

    method, path = args.endpoint.split()

    return {
        "method": method,
        "path": path,
        "api_key": args.api_key,
        "data": args.data,
    }


if __name__ == "__main__":
    args = parse_args()
    cmd = [
        "curl",
        f"http://localhost:31544/api/v2{args['path']}",
        "--silent",
        "--request",
        args["method"],
        "--header",
        f"Authorization: Bearer {args['api_key']}",
    ]
    if args["data"]:
        cmd.extend(["--data", args["data"]])

    print(coloured("-> " + " ".join(shlex.quote(c) for c in cmd), "blue"))
    output = subprocess.check_output(cmd)
    print(json.dumps(json.loads(output), indent=2))
