# Canonical BYOC diagnosis helpers.
# Requires: clinic-auth.sh and cluster-metadata/scripts/clinic-cluster.sh.

_clinic_byoc_diagnostics_url() {
    local cluster_id="$1"
    local suffix="$2"
    shift 2

    local org_id encoded_cluster_id base_url
    org_id=$(_clinic_canonical_org_id_from_cluster_id "$cluster_id") || return 1
    encoded_cluster_id=$(_clinic_path_segment "$cluster_id") || return 1
    base_url="${CLINIC_ENDPOINT}/data-proxy/api/v1/orgs/${org_id}/clusters/${encoded_cluster_id}/${suffix}"

    python3 - "$base_url" "$@" <<'PY'
import sys
import urllib.parse

base = sys.argv[1]
items = sys.argv[2:]
if items[:1] == ["__clinic_query_lines__"]:
    items = sys.argv[3].splitlines() if len(sys.argv) > 3 else []
pairs = []
for item in items:
    key, separator, value = item.partition("=")
    if not separator or not key:
        raise SystemExit(f"invalid query argument {item!r}; expected key=value")
    pairs.append((key, value))
print(base + ("?" + urllib.parse.urlencode(pairs) if pairs else ""))
PY
}

_clinic_byoc_diagnostics_get() {
    local cluster_id="$1"
    local suffix="$2"
    shift 2

    _ensure_clinic_auth || return 1
    local url
    url=$(_clinic_byoc_diagnostics_url "$cluster_id" "$suffix" "$@") || return 1
    curl -sS --fail-with-body "$url" \
        -H "Authorization: Bearer ${CLINIC_API_KEY}"
}

clinic_byoc_slow_query_available_fields() {
    if [ $# -lt 1 ]; then
        echo "usage: clinic_byoc_slow_query_available_fields <cluster_id>" >&2
        return 2
    fi
    _clinic_byoc_diagnostics_get "$1" "slow-queries/available-fields"
}

clinic_byoc_slow_query_list() {
    if [ $# -lt 3 ]; then
        echo "usage: clinic_byoc_slow_query_list <cluster_id> <begin_unix_sec> <end_unix_sec> [limit] [orderBy] [desc] [fields] [text] [digest] [show_internal] [db_csv] [plans_csv]" >&2
        return 2
    fi

    local cluster_id="$1"
    local begin_time="$2"
    local end_time="$3"
    local limit="${4:-100}"
    local order_by="${5:-timestamp}"
    local desc="${6:-false}"
    local fields="${7:-query,timestamp,query_time,memory_max}"
    local text="${8:-}"
    local digest="${9:-}"
    local show_internal="${10:-false}"
    local db_csv="${11:-}"
    local plans_csv="${12:-}"
    local query_args

    query_args=$(python3 - "$begin_time" "$end_time" "$limit" "$order_by" "$desc" "$fields" "$text" "$digest" "$show_internal" "$db_csv" "$plans_csv" <<'PY'
import sys

(begin_time, end_time, limit, order_by, desc, fields, text, digest,
 show_internal, db_csv, plans_csv) = sys.argv[1:]
pairs = [
    ("begin_time", begin_time),
    ("end_time", end_time),
    ("limit", limit),
    ("orderBy", order_by),
    ("desc", desc),
    ("fields", fields),
    ("show_internal", show_internal),
]
if text:
    pairs.append(("text", text))
if digest:
    pairs.append(("digest", digest))
for key, csv in (("db", db_csv), ("plans", plans_csv)):
    pairs.extend((key, value) for value in csv.split(",") if value)
for key, value in pairs:
    print(f"{key}={value}")
PY
) || return 1

    _clinic_byoc_diagnostics_get "$cluster_id" "slow-queries" \
        "__clinic_query_lines__" "$query_args"
}

clinic_byoc_slow_query_detail() {
    if [ $# -lt 4 ]; then
        echo "usage: clinic_byoc_slow_query_detail <cluster_id> <digest> <timestamp> <connect_id> [show_internal]" >&2
        return 2
    fi

    local cluster_id="$1"
    local digest="$2"
    local timestamp="$3"
    local connect_id="$4"
    local show_internal="${5:-}"
    set -- "digest=$digest" "timestamp=$timestamp" "connect_id=$connect_id"
    [ -n "$show_internal" ] && set -- "$@" "show_internal=$show_internal"
    _clinic_byoc_diagnostics_get "$cluster_id" "slow-queries/detail" "$@"
}

clinic_byoc_top_sql_instances() {
    if [ $# -lt 3 ]; then
        echo "usage: clinic_byoc_top_sql_instances <cluster_id> <start_unix_sec> <end_unix_sec>" >&2
        return 2
    fi
    _clinic_byoc_diagnostics_get "$1" "top-sql/instances" "start=$2" "end=$3"
}

clinic_byoc_top_sql_summary() {
    if [ $# -lt 7 ]; then
        echo "usage: clinic_byoc_top_sql_summary <cluster_id> <start_unix_sec> <end_unix_sec> <window> <top> <instance> <instance_type>" >&2
        return 2
    fi
    _clinic_byoc_diagnostics_get "$1" "top-sql/summary" \
        "start=$2" "end=$3" "window=$4" "top=$5" "instance=$6" "instance_type=$7"
}

clinic_byoc_statements_available_fields() {
    if [ $# -lt 1 ]; then
        echo "usage: clinic_byoc_statements_available_fields <cluster_id>" >&2
        return 2
    fi
    _clinic_byoc_diagnostics_get "$1" "statements/available-fields"
}

clinic_byoc_statements_statement_types() {
    if [ $# -lt 1 ]; then
        echo "usage: clinic_byoc_statements_statement_types <cluster_id>" >&2
        return 2
    fi
    _clinic_byoc_diagnostics_get "$1" "statements/statement-types"
}

clinic_byoc_statements_list() {
    if [ $# -lt 3 ]; then
        echo "usage: clinic_byoc_statements_list <cluster_id> <begin_unix_sec> <end_unix_sec> [schemas_csv] [stmt_types_csv] [text] [fields]" >&2
        return 2
    fi

    local cluster_id="$1"
    local begin_time="$2"
    local end_time="$3"
    local schemas_csv="${4:-}"
    local stmt_types_csv="${5:-}"
    local text="${6:-}"
    local fields="${7:-}"
    local query_args
    query_args=$(python3 - "$begin_time" "$end_time" "$schemas_csv" "$stmt_types_csv" "$text" "$fields" <<'PY'
import sys

begin_time, end_time, schemas_csv, stmt_types_csv, text, fields = sys.argv[1:]
pairs = [("begin_time", begin_time), ("end_time", end_time)]
for key, csv in (("schemas", schemas_csv), ("stmt_types", stmt_types_csv)):
    pairs.extend((key, value) for value in csv.split(",") if value)
if text:
    pairs.append(("text", text))
if fields:
    pairs.append(("fields", fields))
for key, value in pairs:
    print(f"{key}={value}")
PY
) || return 1

    _clinic_byoc_diagnostics_get "$cluster_id" "statements" \
        "__clinic_query_lines__" "$query_args"
}

clinic_byoc_statements_plans() {
    if [ $# -lt 4 ]; then
        echo "usage: clinic_byoc_statements_plans <cluster_id> <begin_unix_sec> <end_unix_sec> <digest> [schema_name]" >&2
        return 2
    fi

    local cluster_id="$1"
    local begin_time="$2"
    local end_time="$3"
    local digest="$4"
    local schema_name="${5:-}"
    set -- "begin_time=$begin_time" "end_time=$end_time" "digest=$digest"
    [ -n "$schema_name" ] && set -- "$@" "schema_name=$schema_name"
    _clinic_byoc_diagnostics_get "$cluster_id" "statements/plans" "$@"
}

clinic_byoc_statements_plan_detail() {
    if [ $# -lt 4 ]; then
        echo "usage: clinic_byoc_statements_plan_detail <cluster_id> <begin_unix_sec> <end_unix_sec> <digest> [plans_csv] [schema_name]" >&2
        return 2
    fi

    local cluster_id="$1"
    local begin_time="$2"
    local end_time="$3"
    local digest="$4"
    local plans_csv="${5:-}"
    local schema_name="${6:-}"
    local query_args
    query_args=$(python3 - "$begin_time" "$end_time" "$digest" "$plans_csv" "$schema_name" <<'PY'
import sys

begin_time, end_time, digest, plans_csv, schema_name = sys.argv[1:]
pairs = [("begin_time", begin_time), ("end_time", end_time), ("digest", digest)]
pairs.extend(("plans", value) for value in plans_csv.split(",") if value)
if schema_name:
    pairs.append(("schema_name", schema_name))
for key, value in pairs:
    print(f"{key}={value}")
PY
) || return 1

    _clinic_byoc_diagnostics_get "$cluster_id" "statements/plan-detail" \
        "__clinic_query_lines__" "$query_args"
}

clinic_byoc_continuous_profiling_group_profiles() {
    if [ $# -lt 3 ]; then
        echo "usage: clinic_byoc_continuous_profiling_group_profiles <physical_byoc_host_cluster_id> <begin_unix_sec> <end_unix_sec>" >&2
        return 2
    fi
    _clinic_byoc_diagnostics_get "$1" "continuous-profiling/group-profiles" \
        "begin_time=$2" "end_time=$3"
}

clinic_byoc_continuous_profiling_group_detail() {
    if [ $# -lt 2 ]; then
        echo "usage: clinic_byoc_continuous_profiling_group_detail <physical_byoc_host_cluster_id> <ts>" >&2
        return 2
    fi

    local encoded_ts
    encoded_ts=$(_clinic_path_segment "$2") || return 1
    _clinic_byoc_diagnostics_get "$1" "continuous-profiling/group-profiles/${encoded_ts}"
}
