#!/usr/bin/env python3
"""Read-only New Relic APM queries via NerdGraph NRQL.

Standard library only. Never prints the API key. Only SELECT queries are sent.

Configuration comes from the environment or from the first `.env` / `newrelic.env` found in the
current directory, the git top-level or their parents (or the file named by NEW_RELIC_ENV_FILE):

    NEW_RELIC_API_KEY      User key (starts with NRAK-)
    NEW_RELIC_ACCOUNT_ID   numeric account id
    NEW_RELIC_REGION       eu | us
    NEW_RELIC_APP          default appName (optional)
    NEW_RELIC_APP_<ENV>    appName for --env <env> (optional)

Usage:
  python3 query_newrelic.py --preset apps
  python3 query_newrelic.py --preset top --app my-api --since 1d
  python3 query_newrelic.py --preset transactions --match orders --since 7d
  python3 query_newrelic.py --preset overview --transaction "WebTransaction/..." --since 7d --compare
  python3 query_newrelic.py --preset timeseries --transaction "WebTransaction/..." --since 14d
  python3 query_newrelic.py --preset spans --transaction "WebTransaction/..." --category http
  python3 query_newrelic.py --nrql "SELECT count(*) FROM Transaction SINCE 1 hour ago"
"""
from __future__ import annotations

import argparse
import json
import os
import re
import subprocess
import sys
import urllib.error
import urllib.request
from pathlib import Path
from typing import Any

WINDOW_RE = re.compile(r"^(\d+)(m|h|d)$", re.I)
SELECT_RE = re.compile(r"(?is)^select\b")
ENV_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,31}$")
ENDPOINTS = {
    "eu": "https://api.eu.newrelic.com/graphql",
    "us": "https://api.newrelic.com/graphql",
}

QUERY = """
query($id: Int!, $nrql: Nrql!) {
  actor {
    account(id: $id) {
      nrql(query: $nrql, timeout: 60) {
        results
        metadata { timeWindow { begin end } }
      }
    }
  }
}
"""


class Fail(Exception):
    pass


def candidate_dirs() -> list[Path]:
    dirs: list[Path] = []
    here = Path.cwd().resolve()
    dirs += [here, *here.parents]
    try:
        top = subprocess.run(
            ["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True, timeout=5
        ).stdout.strip()
        if top:
            dirs.insert(0, Path(top))
    except (OSError, subprocess.SubprocessError):
        pass
    return list(dict.fromkeys(dirs))


def find_env_file() -> Path | None:
    explicit = os.environ.get("NEW_RELIC_ENV_FILE")
    if explicit:
        path = Path(explicit).expanduser()
        return path if path.is_file() else None
    for folder in candidate_dirs():
        for name in ("newrelic.env", ".env"):
            candidate = folder / name
            if candidate.is_file():
                return candidate
    return None


def read_env_file(path: Path | None) -> dict[str, str]:
    values: dict[str, str] = {}
    if not path:
        return values
    for raw in path.read_text(encoding="utf-8", errors="replace").splitlines():
        line = raw.strip()
        if line.startswith("export "):
            line = line[7:].strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        values[key.strip().upper()] = value.strip().strip('"').strip("'")
    return values


def env_value(name: str, file_values: dict[str, str]) -> str | None:
    upper = name.upper()
    return os.environ.get(upper) or os.environ.get(name) or file_values.get(upper) or None


def scrub(text: str, secret: str) -> str:
    text = re.sub(r"NRAK-[A-Z0-9]{8,}", "NRAK-[REDACTED]", text)
    if secret and secret in text:
        text = text.replace(secret, "[REDACTED]")
    return text


def key_hint(api_key: str) -> str:
    if api_key.startswith("NRAK-"):
        return " The key is a User key: check it is still valid and has access to this account."
    return (
        " NEW_RELIC_API_KEY must be a User key (it starts with NRAK-), created in the API keys UI "
        "as type User. A license key, an ingest key or a key id cannot run NRQL."
    )


def escape_nrql(value: str, what: str) -> str:
    if any(ch in value for ch in "'\\\n\r`"):
        raise Fail(f"quotes, backslashes and line breaks are not allowed in --{what}")
    return value


def to_since(window: str) -> str:
    match = WINDOW_RE.match(window.strip())
    if not match:
        raise Fail("--since must look like 30m, 1h or 7d")
    count, unit = int(match.group(1)), match.group(2).lower()
    word = {"m": "minute", "h": "hour", "d": "day"}[unit]
    if count != 1:
        word += "s"
    return f"{count} {word} ago"


def assert_select(nrql: str) -> str:
    stripped = re.sub(r"/\*.*?\*/", "", nrql, flags=re.S)
    stripped = re.sub(r"(?m)--.*$", "", stripped).strip().rstrip(";").strip()
    if not SELECT_RE.match(stripped) or ";" in stripped:
        raise Fail("only a single SELECT NRQL statement is allowed")
    return stripped


def build_nrql(args: argparse.Namespace, app: str | None) -> str:
    if args.nrql:
        return assert_select(args.nrql)
    since = to_since(args.since)
    preset = args.preset
    limit = args.limit

    if preset == "apps":
        return f"SELECT uniques(appName) FROM Transaction SINCE {since} LIMIT MAX"

    if not app:
        raise Fail(f"--preset {preset} needs --app (or NEW_RELIC_APP / NEW_RELIC_APP_<ENV>). Try --preset apps.")
    app = escape_nrql(app, "app")

    if preset == "transactions":
        match = escape_nrql(args.match or "", "match")
        if not match:
            raise Fail("--preset transactions needs --match")
        return (
            "SELECT count(*) AS calls, average(duration)*1000 AS avg_ms, "
            "percentile(duration, 95)*1000 AS p95_ms, percentile(duration, 99)*1000 AS p99_ms "
            f"FROM Transaction WHERE appName = '{app}' AND name LIKE '%{match}%' "
            f"FACET name SINCE {since} LIMIT {limit}"
        )

    if preset == "top":
        return (
            "SELECT average(duration)*1000 AS avg_ms, percentile(duration, 95)*1000 AS p95_ms, "
            f"count(*) AS calls FROM Transaction WHERE appName = '{app}' AND transactionType = 'Web' "
            f"FACET name SINCE {since} LIMIT {limit}"
        )

    transaction = escape_nrql(args.transaction or "", "transaction")
    if not transaction:
        raise Fail(f"--preset {preset} needs --transaction (exact name; find it with --preset transactions)")

    where = f"appName = '{app}' AND name = '{transaction}'"
    if preset == "overview":
        nrql = (
            "SELECT count(*) AS calls, average(duration)*1000 AS avg_ms, "
            "percentile(duration, 50)*1000 AS p50_ms, percentile(duration, 95)*1000 AS p95_ms, "
            "percentile(duration, 99)*1000 AS p99_ms, average(databaseDuration)*1000 AS db_ms, "
            "average(externalDuration)*1000 AS ext_ms, average(databaseCallCount) AS db_calls, "
            "average(externalCallCount) AS ext_calls, "
            "percentage(count(*), WHERE error IS true) AS error_pct "
            f"FROM Transaction WHERE {where} SINCE {since}"
        )
        if args.compare:
            nrql += f" COMPARE WITH {since}"
        return nrql

    if preset == "timeseries":
        bucket = "1 hour" if WINDOW_RE.match(args.since) and args.since.lower().endswith(("m", "h")) else "1 day"
        return (
            "SELECT average(duration)*1000 AS avg_ms, percentile(duration, 95)*1000 AS p95_ms, "
            f"count(*) AS calls FROM Transaction WHERE {where} SINCE {since} TIMESERIES {bucket}"
        )

    # Child http/datastore spans do not carry the transaction name: they share trace.id with the
    # root span, so select the traces first and facet the children.
    category = escape_nrql(args.category, "category")
    return (
        "SELECT average(duration.ms) AS avg_ms, percentile(duration.ms, 95) AS p95_ms, "
        "sum(duration.ms) AS total_ms, count(*) AS calls "
        f"FROM Span WHERE appName = '{app}' AND category = '{category}' "
        f"AND trace.id IN (SELECT uniques(trace.id, 500) FROM Span WHERE appName = '{app}' "
        f"AND name = '{transaction}' LIMIT 500) "
        f"FACET name SINCE {since} LIMIT {limit}"
    )


def post_nrql(endpoint: str, api_key: str, account_id: int, nrql: str) -> dict[str, Any]:
    body = json.dumps({"query": QUERY, "variables": {"id": account_id, "nrql": nrql}}).encode("utf-8")
    request = urllib.request.Request(
        endpoint,
        data=body,
        headers={"Content-Type": "application/json", "API-Key": api_key},
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=90) as response:
            payload = json.loads(response.read().decode("utf-8"))
    except urllib.error.HTTPError as exc:
        detail = exc.read().decode("utf-8", errors="replace")
        hint = key_hint(api_key) if exc.code in (401, 403) else ""
        raise Fail(scrub(f"NerdGraph HTTP {exc.code}: {detail[:500]}{hint}", api_key)) from None
    except urllib.error.URLError as exc:
        raise Fail(scrub(f"NerdGraph unreachable: {exc.reason}", api_key)) from None
    except json.JSONDecodeError:
        raise Fail("NerdGraph returned something that is not JSON") from None
    if payload.get("errors"):
        message = "; ".join(str(error.get("message", "")) for error in payload["errors"])
        raise Fail(scrub(f"NerdGraph: {message}", api_key))
    return payload


def main() -> int:
    parser = argparse.ArgumentParser(description="Read-only New Relic NRQL via NerdGraph")
    parser.add_argument("--preset", choices=["apps", "transactions", "top", "overview", "timeseries", "spans"])
    parser.add_argument("--nrql", help="ad-hoc SELECT NRQL; mutually exclusive with --preset")
    parser.add_argument("--app", help="exact appName (default: NEW_RELIC_APP_<ENV> or NEW_RELIC_APP)")
    parser.add_argument("--env", help="environment name used to pick NEW_RELIC_APP_<ENV>")
    parser.add_argument("--match", help="fragment of Transaction.name for --preset transactions")
    parser.add_argument("--transaction", help="exact Transaction.name")
    parser.add_argument("--category", default="http", choices=["http", "datastore"])
    parser.add_argument("--since", default="1d", help="30m, 1h, 7d (default 1d)")
    parser.add_argument("--compare", action="store_true", help="with --preset overview, compare with the previous window")
    parser.add_argument("--limit", type=int, default=25, help="facet size, 1-100")
    args = parser.parse_args()

    if bool(args.preset) == bool(args.nrql):
        raise Fail("pass exactly one of --preset or --nrql")
    if not 1 <= args.limit <= 100:
        raise Fail("--limit must be between 1 and 100")

    file_values = read_env_file(find_env_file())
    api_key = env_value("NEW_RELIC_API_KEY", file_values)
    account = env_value("NEW_RELIC_ACCOUNT_ID", file_values)
    region = (env_value("NEW_RELIC_REGION", file_values) or "").lower()
    missing = [
        name
        for name, value in (
            ("NEW_RELIC_API_KEY", api_key),
            ("NEW_RELIC_ACCOUNT_ID", account),
            ("NEW_RELIC_REGION", region if region in ENDPOINTS else None),
        )
        if not value
    ]
    if missing:
        raise Fail("missing or invalid: " + ", ".join(missing) + " (NEW_RELIC_REGION must be eu or us)")
    try:
        account_id = int(str(account))
    except ValueError:
        raise Fail("NEW_RELIC_ACCOUNT_ID must be a number") from None

    env_name = None
    if args.env:
        env_name = args.env.strip().lower()
        if not ENV_RE.match(env_name):
            raise Fail("invalid --env: use letters, digits, '-' or '_'")
    app = args.app
    if not app and env_name:
        app = env_value(f"NEW_RELIC_APP_{env_name.upper().replace('-', '_')}", file_values)
    if not app:
        app = env_value("NEW_RELIC_APP", file_values)

    nrql = build_nrql(args, app)
    payload = post_nrql(ENDPOINTS[region], str(api_key), account_id, nrql)
    account_node = ((payload.get("data") or {}).get("actor") or {}).get("account") or {}
    nrql_node = account_node.get("nrql") or {}
    window = (nrql_node.get("metadata") or {}).get("timeWindow") or {}
    json.dump(
        {
            "ok": True,
            "region": region,
            "app": app if not args.nrql else None,
            "env": env_name,
            "nrql": nrql,
            "begin": window.get("begin"),
            "end": window.get("end"),
            "results": nrql_node.get("results") or [],
        },
        sys.stdout,
        ensure_ascii=False,
    )
    sys.stdout.write("\n")
    return 0


if __name__ == "__main__":
    try:
        sys.stdout.reconfigure(encoding="utf-8")
        sys.stderr.reconfigure(encoding="utf-8")
    except Exception:
        pass
    try:
        raise SystemExit(main())
    except Fail as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        raise SystemExit(1)
