"""Helper: run SQL against Metabase BigQuery db=6 via REST API.

Usage:
    python3 mbq.py "SELECT 1"
    python3 mbq.py < query.sql
Reads API key from `pass metabase/aurgi-api-key`.
Prints columns header + rows as TSV.
"""
import os
import sys
import json
import subprocess

sys.path.insert(0, "python/functions")
from metabase import MetabaseClient, metabase_execute_query

MB_URL = "https://reports.autingo.es"
DB_ID = 6


def get_key():
    return subprocess.check_output(["pass", "show", "metabase/aurgi-api-key"]).decode().splitlines()[0].strip()


def run(sql, max_results=2000):
    import httpx
    c = MetabaseClient(MB_URL, get_key())
    try:
        res = metabase_execute_query(c, DB_ID, sql, max_results=max_results)
    except httpx.HTTPStatusError as e:
        print("HTTP", e.response.status_code, e.response.text[:3000])
        return
    data = res.get("data", {})
    cols = [col.get("display_name") or col.get("name") for col in data.get("cols", [])]
    rows = data.get("rows", [])
    # error?
    if res.get("error") or (res.get("status") and res.get("status") != "completed"):
        print("ERROR:", json.dumps(res.get("error") or res, ensure_ascii=False)[:2000])
        return
    print("\t".join(str(x) for x in cols))
    for r in rows:
        print("\t".join("" if v is None else str(v) for v in r))
    print(f"-- {len(rows)} rows", file=sys.stderr)


if __name__ == "__main__":
    if len(sys.argv) > 1:
        sql = sys.argv[1]
    else:
        sql = sys.stdin.read()
    run(sql)
