#!/usr/bin/env python3
"""Query application logs in Kibana and group errors by signature.

Read-only. Standard library only. Never prints credentials.

Configuration comes from the environment or from the first `.env` / `kibana.env` found in the
current directory or its parents (or the file named by KIBANA_ENV_FILE). Most specific key wins:

    KIBANA_<NAME>_<TENANT>_<ENV>  ->  KIBANA_<NAME>_<TENANT>  ->  KIBANA_<NAME>_<ENV>  ->  KIBANA_<NAME>

for NAME in HOST, USER, PASSWORD, SPACE, APP, INDEX_PATTERN. Keys are case-insensitive.

Usage:
  python3 query_kibana.py                                   # last hour, ERROR/FATAL, default env
  python3 query_kibana.py --env pre --since 24h --text "NullReferenceException"
  python3 query_kibana.py --tenant acme --env pro --since 2h --baseline 24h
  python3 query_kibana.py --correlation 1758100000123       # full trace of one request
"""
from __future__ import annotations

import argparse
import base64
import json
import os
import re
import ssl
import sys
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable

ENV_ALIASES = {
    "prod": "pro",
    "production": "pro",
    "produccion": "pro",
    "producción": "pro",
    "preprod": "pre",
    "prepro": "pre",
    "staging": "pre",
    "tes": "test",
    "dev": "des",
    "desarrollo": "des",
    "development": "des",
}
NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,31}$")
WINDOW_RE = re.compile(r"^(\d+)(m|h|d)$", re.I)
ISO_RE = re.compile(r"^\d{4}-\d{2}-\d{2}")
CORR_VALUE_RE = re.compile(r"^[\w.:-]{4,128}$")
ALL_LEVELS = ["ERROR", "FATAL", "WARN", "INFO", "DEBUG"]

FIELD_DEFAULTS = {
    "APP": "applicationName",
    "LEVEL": "level",
    "LOGGER": "logger",
    "LOCATION": "location",
    "MESSAGE": "message",
    "EXCEPTION": "exception",
    "HOST": "host",
    "CORRELATION": "",
}

REDACT_PATTERNS = [
    (re.compile(r"(?i)(x-api-key\s*:\s*)\S+"), r"\1[REDACTED]"),
    (re.compile(r"(?i)(authorization\s*:\s*)(?:bearer\s+|basic\s+)?\S+"), r"\1[REDACTED]"),
    (re.compile(r"(?i)(bearer\s+)\S+"), r"\1[REDACTED]"),
    (re.compile(r"(?i)((?:api[_-]?key|password|passwd|secret|token)\s*[=:]\s*)\S+"), r"\1[REDACTED]"),
    (re.compile(r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b"), "[email]"),
    (re.compile(r"\b[XYZ]\d{7}[A-HJ-NP-TV-Z]\b", re.I), "[id-doc]"),
    (re.compile(r"\b\d{8}[A-HJ-NP-TV-Z]\b"), "[id-doc]"),
    # Phones only when they look like phones (international prefix or separated groups):
    # a bare run of digits may be a functional id and must survive.
    (re.compile(r"(?<![\w+])\+\d{1,3}[\s-]?\d{2,4}[\s-]?\d{3}[\s-]?\d{3,4}(?!\d)"), "[phone]"),
    (re.compile(r"(?<!\d)[6789]\d{2}[\s-]\d{3}[\s-]\d{3}(?!\d)"), "[phone]"),
]
CONN_ID_RE = re.compile(r'(?:Connection|Request) id "[^"]+"', re.I)
ISO_TS_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[^,\s]*")
TRACEPARENT_RE = re.compile(r"(?i)traceparent:\s*\S+")
GUID_RE = re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", re.I)
EXC_OF_TYPE_RE = re.compile(r"(?i)(?:of type|del tipo)\s*:?\s*'?([\w.`+]+)")
EXC_TYPE_LINE_RE = re.compile(r"^([A-Za-z_][\w.`+]*(?:Exception|Error)(?:`\d+)?)\b")
STACK_RE = re.compile(r"^\s*(?:at\s+|File \")")
BOILERPLATE_RE = re.compile(
    r"(?i)^(an? (?:unhandled )?exception (?:has )?occurr|ocurri[oó] una excepci[oó]n|"
    r"the exception handler configured|an unhandled exception|--- end of|traceback \(most recent)"
)
AGG_ERROR_RE = re.compile(
    r"(?i)fielddata|no mapping|illegal_argument|aggregat|keyword|Text fields are not optimised"
)


class SearchError(RuntimeError):
    pass


def die(message: str, code: int = 1) -> None:
    print(f"ERROR: {message}", file=sys.stderr)
    sys.exit(code)


# --------------------------------------------------------------------------- configuration


def find_env_file() -> Path | None:
    explicit = os.environ.get("KIBANA_ENV_FILE")
    if explicit:
        path = Path(explicit).expanduser()
        return path if path.is_file() else None
    here = Path.cwd().resolve()
    for folder in [here, *here.parents]:
        for name in ("kibana.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


class Config:
    def __init__(self, file_values: dict[str, str], env_name: str, tenant: str | None) -> None:
        self.file_values = file_values
        self.env_name = env_name
        self.tenant = tenant
        self._environ = {key.upper(): value for key, value in os.environ.items()}

    def raw(self, key: str) -> str | None:
        upper = key.upper()
        value = self._environ.get(upper) or self.file_values.get(upper)
        return value or None

    def keys_for(self, name: str) -> list[str]:
        env_u = self.env_name.upper().replace("-", "_")
        keys: list[str] = []
        if self.tenant:
            tenant_u = self.tenant.upper().replace("-", "_")
            keys += [f"KIBANA_{name}_{tenant_u}_{env_u}", f"KIBANA_{name}_{tenant_u}"]
        keys += [f"KIBANA_{name}_{env_u}", f"KIBANA_{name}"]
        return keys

    def resolve(self, name: str, default: str | None = None) -> str | None:
        for key in self.keys_for(name):
            value = self.raw(key)
            if value:
                return value
        return default

    def tenant_specific(self, name: str) -> bool:
        return any(self.raw(key) for key in self.keys_for(name)[:2]) if self.tenant else False

    def env_specific(self, name: str) -> bool:
        return any(self.raw(key) for key in self.keys_for(name)[:-1])

    def field(self, name: str) -> str:
        value = self.raw(f"KIBANA_FIELD_{name}")
        return value if value is not None else FIELD_DEFAULTS[name]


# --------------------------------------------------------------------------- text handling


def redact(text: Any) -> str:
    if text is None:
        return ""
    out = str(text).replace("\x00", "")
    for pattern, repl in REDACT_PATTERNS:
        out = pattern.sub(repl, out)
    return out


def normalize_message(text: str, corr_re: re.Pattern[str]) -> str:
    out = redact(text)
    out = corr_re.sub("", out)
    out = CONN_ID_RE.sub("", out)
    out = ISO_TS_RE.sub("", out)
    out = TRACEPARENT_RE.sub("", out)
    out = GUID_RE.sub("<guid>", out)
    out = re.sub(r"https?://[^/\s,]+", "", out)
    out = re.sub(r"\s+", " ", out).strip(" ,")
    return out[:220]


def exception_signature(exc: str) -> tuple[str | None, str | None]:
    if not exc:
        return None, None
    tipo = None
    match = EXC_OF_TYPE_RE.search(exc)
    if match:
        tipo = match.group(1).rstrip(".,;'")
    inner = None
    for raw_line in exc.splitlines():
        line = raw_line.strip()
        if not line or STACK_RE.match(line) or BOILERPLATE_RE.match(line):
            continue
        type_line = EXC_TYPE_LINE_RE.match(line)
        if type_line:
            tipo = tipo or type_line.group(1)
            # Most runtimes print "Type: message" on one line; keep the message part.
            rest = line[type_line.end():].lstrip(":").strip()
            rest = re.sub(r"^--->\s*", "", rest)
            if inner is None and 8 <= len(rest) <= 240:
                inner = rest
            continue
        if inner is None and 8 <= len(line) <= 240:
            inner = line
    return tipo, inner


def get_field(source: dict[str, Any], dotted: str) -> Any:
    """Read `a.b.c` either as a flat key or as nested objects (ECS style)."""
    if not dotted:
        return None
    if dotted in source:
        return source[dotted]
    node: Any = source
    for part in dotted.split("."):
        if not isinstance(node, dict) or part not in node:
            return None
        node = node[part]
    return node


def as_text(value: Any) -> str:
    if value is None:
        return ""
    if isinstance(value, list):
        return "\n".join(as_text(item) for item in value)
    if isinstance(value, dict):
        return json.dumps(value, ensure_ascii=False)
    return str(value)


# --------------------------------------------------------------------------- argument parsing


def parse_name(raw: str, what: str) -> str:
    key = raw.strip().lower()
    key = ENV_ALIASES.get(key, key) if what == "env" else key
    if not NAME_RE.match(key):
        die(f"invalid --{what} '{raw}': use letters, digits, '-' or '_'.")
    return key


def parse_window(since: str) -> str:
    text = since.strip()
    match = WINDOW_RE.match(text)
    if match:
        return f"now-{match.group(1)}{match.group(2).lower()}"
    if ISO_RE.match(text):
        return text
    die(f"invalid --since '{since}'. Use 30m, 1h, 24h, 7d or an ISO datetime.")
    return text


def parse_until(until: str) -> str:
    text = (until or "now").strip()
    if text == "now" or ISO_RE.match(text):
        return text
    match = WINDOW_RE.match(text)
    if match:
        return f"now-{match.group(1)}{match.group(2).lower()}"
    die(f"invalid --until '{until}'. Use now, 30m, 1h, 24h, 7d or an ISO datetime.")
    return text


def parse_levels(raw: str) -> list[str]:
    levels = [part.strip().upper() for part in raw.split(",") if part.strip()]
    levels = ["WARN" if level == "WARNING" else level for level in levels]
    bad = [level for level in levels if level not in ALL_LEVELS]
    if bad:
        die(f"unknown log levels: {', '.join(bad)}")
    if not levels:
        die("at least one --levels value is required")
    return levels


# --------------------------------------------------------------------------- HTTP client


def ssl_context(cfg: Config) -> ssl.SSLContext:
    insecure = (cfg.resolve("INSECURE_TLS") or "").lower() in ("1", "true", "yes")
    if insecure:
        print("WARNING: TLS verification disabled by KIBANA_INSECURE_TLS.", file=sys.stderr)
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        return ctx
    cafile = cfg.resolve("CA_FILE") or os.environ.get("SSL_CERT_FILE") or None
    if cafile and not Path(cafile).expanduser().is_file():
        die("KIBANA_CA_FILE points to a file that does not exist.")
    return ssl.create_default_context(cafile=str(Path(cafile).expanduser()) if cafile else None)


def _error_reason(result: Any) -> str:
    if isinstance(result, dict):
        err = result.get("error") or result.get("message") or result.get("attributes")
        if isinstance(err, dict):
            root = err.get("root_cause")
            if isinstance(root, list) and root and isinstance(root[0], dict):
                return str(root[0].get("reason") or err.get("reason") or "")[:300]
            return str(err.get("reason") or err.get("type") or json.dumps(err)[:300])
        if err:
            return str(err)[:300]
        return ""
    return redact(str(result or ""))[:300]


class KibanaClient:
    def __init__(self, host: str, user: str, password: str, space: str, ctx: ssl.SSLContext) -> None:
        self.host = host.rstrip("/")
        self.space = space
        token = base64.b64encode(f"{user}:{password}".encode()).decode()
        self._headers = {
            "Authorization": f"Basic {token}",
            "kbn-xsrf": "true",
            "Accept": "application/json",
            "Content-Type": "application/json",
        }
        self._ctx = ctx

    @property
    def space_prefix(self) -> str:
        return "" if self.space in ("", "default") else f"/s/{self.space}"

    def _request(self, path: str, method: str = "GET", body: Any | None = None) -> tuple[int, Any]:
        data = None if body is None else json.dumps(body).encode("utf-8")
        req = urllib.request.Request(self.host + path, data=data, headers=self._headers, method=method)
        try:
            with urllib.request.urlopen(req, context=self._ctx, timeout=45) as resp:
                raw = resp.read().decode("utf-8", "replace")
                status = resp.status
        except urllib.error.HTTPError as exc:
            raw = exc.read().decode("utf-8", "replace")
            status = exc.code
            if exc.code == 401:
                die("Kibana returned 401. Check KIBANA_USER / KIBANA_PASSWORD for this env/tenant.")
        except urllib.error.URLError as exc:
            reason = str(exc.reason)
            if "CERTIFICATE_VERIFY_FAILED" in reason:
                die(
                    "TLS certificate not trusted. Point KIBANA_CA_FILE at your CA bundle "
                    "(or, as a last resort, set KIBANA_INSECURE_TLS=true)."
                )
            die(f"cannot reach the Kibana host: {reason}")
            return 0, None
        parsed: Any = None
        if raw:
            try:
                parsed = json.loads(raw)
            except json.JSONDecodeError:
                parsed = raw
        return status, parsed

    def spaces(self) -> list[dict[str, Any]]:
        status, payload = self._request("/api/spaces/space")
        if status == 200 and isinstance(payload, list):
            return payload
        return []

    def version_number(self) -> str:
        status, payload = self._request("/api/status")
        if status == 200 and isinstance(payload, dict):
            version = payload.get("version")
            if isinstance(version, dict):
                return str(version.get("number") or "")
            if isinstance(version, str):
                return version
        return ""

    def data_views(self) -> list[dict[str, Any]]:
        status, payload = self._request(f"{self.space_prefix}/api/data_views")
        if status == 200 and isinstance(payload, dict) and payload.get("data_view"):
            return payload["data_view"]
        status, payload = self._request(
            f"{self.space_prefix}/api/saved_objects/_find?type=index-pattern&per_page=100"
        )
        views: list[dict[str, Any]] = []
        if status == 200 and isinstance(payload, dict):
            for obj in payload.get("saved_objects") or []:
                attrs = obj.get("attributes") or {}
                views.append({"id": obj.get("id"), "title": attrs.get("title"), "name": attrs.get("name")})
        return views

    def search(self, index: str, body: dict[str, Any]) -> dict[str, Any]:
        """One _search: internal search API (with and without space), then the console proxy."""
        errors: list[str] = []
        internal_paths = [f"{self.space_prefix}/internal/search/es", "/internal/search/es"]
        internal_body = {"params": {"index": index, "body": body}}
        for path in dict.fromkeys(internal_paths):
            status, result = self._request(path, method="POST", body=internal_body)
            if status == 200 and isinstance(result, dict):
                raw = result.get("rawResponse") if "rawResponse" in result else result
                if isinstance(raw, dict) and "hits" in raw:
                    return raw
            errors.append(f"{path} -> {status} {_error_reason(result)}")

        quoted = urllib.parse.quote(f"{index}/_search", safe="/*?")
        proxy_paths = [
            f"{self.space_prefix}/api/console/proxy?path={quoted}&method=POST",
            f"/api/console/proxy?path={quoted}&method=POST",
        ]
        for path in dict.fromkeys(proxy_paths):
            status, result = self._request(path, method="POST", body=body)
            if status == 200 and isinstance(result, dict):
                if result.get("error"):
                    raise SearchError(f"Elasticsearch error: {_error_reason(result)}")
                return result
            errors.append(f"{path.split('?')[0]} -> {status} {_error_reason(result)}")

        raise SearchError(
            f"no usable search API on this Kibana (space '{self.space}'). " + " | ".join(errors)[:800]
        )

    def search_with_fallbacks(
        self, index: str, build: Callable[[bool], dict[str, Any]]
    ) -> tuple[dict[str, Any], str | None]:
        """build(use_keyword) -> body. Tries .keyword aggs, bare aggs, then no aggs."""
        attempts = [
            (True, True, None),
            (False, True, "aggregations use bare keyword fields"),
            (False, False, "aggregations unavailable on this cluster; by_* are empty"),
        ]
        last: SearchError | None = None
        for use_keyword, with_aggs, note in attempts:
            body = build(use_keyword)
            if not with_aggs:
                body.pop("aggs", None)
            try:
                return self.search(index, body), note
            except SearchError as exc:
                last = exc
                if not AGG_ERROR_RE.search(str(exc)):
                    raise
        raise last if last else SearchError("search failed")


# --------------------------------------------------------------------------- query building


class Query:
    def __init__(self, cfg: Config, app: str | None, levels: list[str], text: str | None,
                 correlation: str | None) -> None:
        self.app = app
        self.levels = levels
        self.text = text
        self.correlation = correlation
        self.f = {name: cfg.field(name) for name in FIELD_DEFAULTS}

    def kql(self) -> str:
        parts: list[str] = []
        if self.app and self.f["APP"]:
            parts.append(f'{self.f["APP"]}:"{self.app}"')
        parts.append("(" + " or ".join(f'{self.f["LEVEL"]}:"{lv}"' for lv in self.levels) + ")")
        if self.correlation and self.f["CORRELATION"]:
            parts.append(f'{self.f["CORRELATION"]}:"{self.correlation}"')
        elif self.text:
            parts.append('"' + self.text.replace('"', '\\"') + '"')
        return " and ".join(parts)

    def body(self, gte: str, until: str, size: int, use_keyword: bool, ascending: bool,
             with_aggs: bool = True) -> dict[str, Any]:
        # query_string matches both keyword fields and text fields with a .keyword subfield.
        level_or = " OR ".join(self.levels)
        clauses = [f'{self.f["LEVEL"]}:({level_or})']
        if self.app and self.f["APP"]:
            clauses.insert(0, f'{self.f["APP"]}:"{self.app}"')
        filters: list[dict[str, Any]] = [
            {"query_string": {"query": " AND ".join(clauses)}},
            {"range": {"@timestamp": {"gte": gte, "lte": until}}},
        ]
        must: list[dict[str, Any]] = []
        if self.correlation and self.f["CORRELATION"]:
            filters.append({"match_phrase": {self.f["CORRELATION"]: self.correlation}})
        elif self.text:
            search_fields = [self.f[n] for n in ("MESSAGE", "EXCEPTION", "LOGGER", "LOCATION") if self.f[n]]
            must.append(
                {"simple_query_string": {"query": self.text, "fields": search_fields, "default_operator": "and"}}
            )
        source = ["@timestamp"] + [v for k, v in self.f.items() if v and k != "CORRELATION"]
        if self.f["CORRELATION"]:
            source.append(self.f["CORRELATION"])
        body: dict[str, Any] = {
            "size": size,
            "track_total_hits": True,
            "sort": [{"@timestamp": "asc" if ascending else "desc"}],
            "_source": source,
            "query": {"bool": {"filter": filters, "must": must}},
        }
        if with_aggs:
            body["aggs"] = self.aggs(use_keyword, histogram_interval(gte, until))
        return body

    def aggs(self, use_keyword: bool, interval: str) -> dict[str, Any]:
        suffix = ".keyword" if use_keyword else ""
        aggs: dict[str, Any] = {
            "by_level": {"terms": {"field": f'{self.f["LEVEL"]}{suffix}', "size": 10}},
            "timeline": {
                "date_histogram": {"field": "@timestamp", "fixed_interval": interval, "min_doc_count": 0}
            },
        }
        if self.f["LOGGER"]:
            aggs["by_logger"] = {"terms": {"field": f'{self.f["LOGGER"]}{suffix}', "size": 25}}
        if self.f["LOCATION"]:
            aggs["by_location"] = {"terms": {"field": f'{self.f["LOCATION"]}{suffix}', "size": 25}}
        return aggs


def histogram_interval(gte: str, until: str) -> str:
    """~24-48 buckets for relative windows; 1h otherwise."""
    match = re.match(r"^now-(\d+)([mhd])$", gte)
    if not match or until != "now":
        return "1h"
    minutes = int(match.group(1)) * {"m": 1, "h": 60, "d": 1440}[match.group(2)]
    for step, label in ((5, "1m"), (60, "5m"), (240, "10m"), (1440, "30m"), (4320, "1h"), (20160, "6h")):
        if minutes <= step:
            return label
    return "1d"


def baseline_window(gte: str, baseline: str) -> tuple[str, str]:
    """Window of `baseline` length ending where the main window starts. Relative windows only."""
    match = WINDOW_RE.match(baseline.strip())
    main = re.match(r"^now-(\d+)([mhd])$", gte)
    if not match or not main:
        die("--baseline needs relative windows (e.g. --since 2h --baseline 24h)")
    unit = {"m": 1, "h": 60, "d": 1440}
    main_minutes = int(main.group(1)) * unit[main.group(2)]
    base_minutes = int(match.group(1)) * unit[match.group(2).lower()]
    return f"now-{main_minutes + base_minutes}m", gte


def match_data_view(views: list[dict[str, Any]], index: str) -> dict[str, Any] | None:
    bare = index.rstrip("*").rstrip("-")
    for view in views:
        if (view.get("title") or "") == index:
            return view
    for view in views:
        if (view.get("name") or "").lower() == bare.lower():
            return view
    for view in views:
        if (view.get("title") or "").lower().startswith(bare.lower()):
            return view
    return None


def discover_url(host: str, space_prefix: str, view_id: str | None, kql: str, gte: str,
                 until: str, version: str) -> str:
    g_time = f"time:(from:'{gte}',to:'{until}')" if ISO_RE.match(gte) else f"time:(from:{gte},to:{until})"
    query = urllib.parse.quote(kql, safe="")
    index_part = f"index:'{view_id}'," if view_id else ""
    try:
        major = int(version.split(".", 1)[0]) if version else 8
    except ValueError:
        major = 8
    # Kibana 7 Discover lives under the legacy kibana app; 8+ uses /app/discover.
    app = "discover#/" if major >= 8 else "kibana#/discover"
    return (
        f"{host.rstrip('/')}{space_prefix}/app/{app}"
        f"?_g=(filters:!(),refreshInterval:(pause:!t,value:0),{g_time})"
        f"&_a=({index_part}interval:auto,query:(language:kuery,query:'{query}'),"
        f"sort:!(!('@timestamp',desc)))"
    )


# --------------------------------------------------------------------------- grouping


class Grouper:
    def __init__(self, q: Query, corr_re: re.Pattern[str]) -> None:
        self.f = q.f
        self.corr_re = corr_re

    def get(self, source: dict[str, Any], name: str) -> str:
        return as_text(get_field(source, self.f[name]))

    def correlation_of(self, source: dict[str, Any]) -> str | None:
        if self.f["CORRELATION"]:
            value = self.get(source, "CORRELATION")
            return value or None
        match = self.corr_re.search(self.get(source, "MESSAGE"))
        return match.group(1) if match and match.groups() else (match.group(0) if match else None)

    def signature(self, source: dict[str, Any]) -> str:
        logger = self.get(source, "LOGGER").rsplit(".", 1)[-1]
        tipo, inner = exception_signature(self.get(source, "EXCEPTION"))
        norm = normalize_message(self.get(source, "MESSAGE"), self.corr_re)
        inner = redact(inner) if inner else inner
        if tipo and inner:
            return f"{tipo} | {inner}"
        if tipo:
            return f"{tipo} | {norm or logger}"
        if inner:
            return f"{logger} | {inner}"
        return f"{logger} | {norm or '(no message)'}"

    def group(self, hits: list[dict[str, Any]]) -> list[dict[str, Any]]:
        buckets: dict[str, dict[str, Any]] = {}
        for hit in hits:
            source = hit.get("_source") or {}
            key = self.signature(source)
            ts = as_text(source.get("@timestamp"))
            if key not in buckets:
                buckets[key] = {
                    "signature": key,
                    "count": 0,
                    "level": self.get(source, "LEVEL") or None,
                    "logger": self.get(source, "LOGGER") or None,
                    "location": self.get(source, "LOCATION") or None,
                    "first_seen": ts,
                    "last_seen": ts,
                    "sample_message": redact(self.get(source, "MESSAGE"))[:500],
                    "sample_exception": redact(self.get(source, "EXCEPTION"))[:1500],
                    "sample_id": hit.get("_id"),
                    "sample_index": hit.get("_index"),
                    "sample_correlation": self.correlation_of(source),
                    "hosts": set(),
                }
            group = buckets[key]
            group["count"] += 1
            if ts:
                if not group["last_seen"] or ts > group["last_seen"]:
                    group["last_seen"] = ts
                if not group["first_seen"] or ts < group["first_seen"]:
                    group["first_seen"] = ts
            host = self.get(source, "HOST")
            if host:
                group["hosts"].add(host)
        grouped = []
        for group in buckets.values():
            group["hosts"] = sorted(group["hosts"])
            grouped.append(group)
        grouped.sort(key=lambda item: (-item["count"], item["signature"]))
        return grouped

    def event(self, hit: dict[str, Any]) -> dict[str, Any]:
        source = hit.get("_source") or {}
        exc = redact(self.get(source, "EXCEPTION"))
        return {
            "timestamp": source.get("@timestamp"),
            "level": self.get(source, "LEVEL") or None,
            "logger": self.get(source, "LOGGER") or None,
            "location": self.get(source, "LOCATION") or None,
            "host": self.get(source, "HOST") or None,
            "message": redact(self.get(source, "MESSAGE"))[:600],
            "exception": exc[:1500] if exc else None,
        }


def agg_buckets(aggs: dict[str, Any], name: str) -> list[dict[str, Any]]:
    return [
        {"key": bucket.get("key_as_string") or bucket["key"], "count": bucket["doc_count"]}
        for bucket in (aggs.get(name) or {}).get("buckets") or []
    ]


def hits_total(result: dict[str, Any]) -> int:
    total_obj = (result.get("hits") or {}).get("total") or 0
    return int(total_obj.get("value") or 0) if isinstance(total_obj, dict) else int(total_obj or 0)


# --------------------------------------------------------------------------- main


def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Query application logs in Kibana (read-only)")
    parser.add_argument("--env", default=None, help="pro | pre | test | des | any name (default: KIBANA_DEFAULT_ENV or pro)")
    parser.add_argument("--tenant", default=None, help="optional tenant/organisation with its own Kibana")
    parser.add_argument("--since", default="1h", help="window: 30m, 1h, 24h, 7d, or ISO datetime")
    parser.add_argument("--until", default="now", help="range end: now, 30m, 1h, or ISO datetime")
    parser.add_argument("--levels", default="ERROR,FATAL", help="comma-separated levels (default: ERROR,FATAL)")
    parser.add_argument("--text", default=None, help="free-text filter (message, exception, logger, location)")
    parser.add_argument("--correlation", default=None, help="correlation id: chronological trace of that request, all levels")
    parser.add_argument("--baseline", default=None, help="relative window before --since (e.g. 24h): marks new signatures")
    parser.add_argument("--app", default=None, help="application name (default: KIBANA_APP; none = no app filter)")
    parser.add_argument("--index", default=None, help="index pattern (default: KIBANA_INDEX_PATTERN or {env}-*)")
    parser.add_argument("--space", default=None, help="Kibana space id (default: KIBANA_SPACE or auto)")
    parser.add_argument("--size", type=int, default=200, help="max hits to group (1-1000, default 200)")
    return parser.parse_args(argv)


def main(argv: list[str] | None = None) -> int:
    args = parse_args(argv)
    if args.size < 1 or args.size > 1000:
        die("--size must be between 1 and 1000")

    file_values = read_env_file(find_env_file())
    probe = Config(file_values, "pro", None)
    env_name = parse_name(args.env or probe.raw("KIBANA_DEFAULT_ENV") or "pro", "env")
    tenant = parse_name(args.tenant, "tenant") if args.tenant else None
    cfg = Config(file_values, env_name, tenant)

    if tenant and not cfg.tenant_specific("HOST"):
        die(
            f"tenant '{tenant}' has no Kibana configured. Add to your .env:\n"
            f"  KIBANA_HOST_{tenant.upper()}=https://<kibana-host>\n"
            f"  KIBANA_USER_{tenant.upper()}=<user>\n"
            f"  KIBANA_PASSWORD_{tenant.upper()}=<password>"
        )
    own_host_envs = {
        e.strip().lower() for e in (cfg.raw("KIBANA_ENVS_WITH_OWN_HOST") or "").split(",") if e.strip()
    }
    if env_name in own_host_envs and not cfg.env_specific("HOST"):
        die(
            f"env '{env_name}' lives on its own Kibana. Add KIBANA_HOST_{env_name.upper()}=https://<kibana-host> "
            "(and _USER / _PASSWORD if they differ) instead of querying the default host."
        )

    host = cfg.resolve("HOST")
    user = cfg.resolve("USER")
    password = cfg.resolve("PASSWORD")
    if not host or not user or not password:
        die("KIBANA_HOST, KIBANA_USER and KIBANA_PASSWORD must be set (environment or .env).")
    if not re.match(r"^https?://", host):
        die("KIBANA_HOST must start with https:// (or http://).")

    app = args.app or cfg.resolve("APP")
    levels = parse_levels(args.levels)
    gte = parse_window(args.since)
    until = parse_until(args.until)
    index = args.index or (cfg.resolve("INDEX_PATTERN") or "{env}-*")
    index = index.replace("{env}", env_name).replace("{tenant}", tenant or "")
    if not re.match(r"^[\w.*,:-]+$", index):
        die(f"invalid index pattern '{index}'")
    text = args.text.strip() if args.text else None

    corr_regex = cfg.raw("KIBANA_CORRELATION_REGEX") or r"\[(\d{10,})\]"
    try:
        corr_re = re.compile(corr_regex)
    except re.error:
        die("KIBANA_CORRELATION_REGEX is not a valid regular expression.")
        return 1
    correlation = args.correlation.strip().strip("[]") if args.correlation else None
    if correlation:
        if not CORR_VALUE_RE.match(correlation):
            die("--correlation must be a plain id (letters, digits, '.', ':', '-', '_').")
        levels = list(ALL_LEVELS)
        if not cfg.field("CORRELATION"):
            text = f'"{correlation}"'

    query = Query(cfg, app, levels, text, correlation)
    grouper = Grouper(query, corr_re)

    space = args.space or cfg.resolve("SPACE") or "default"
    client = KibanaClient(host, user, password, space, ssl_context(cfg))
    if not args.space and not cfg.resolve("SPACE"):
        ids = [item.get("id") for item in client.spaces() if item.get("id")]
        if client.space not in ids and len(ids) == 1:
            client.space = ids[0]
    kibana_version = client.version_number()

    try:
        result, agg_note = client.search_with_fallbacks(
            index, lambda kw: query.body(gte, until, args.size, kw, ascending=bool(correlation))
        )
    except SearchError as exc:
        die(redact(str(exc)))
        return 1

    hits = (result.get("hits") or {}).get("hits") or []
    total = hits_total(result)
    shards = result.get("_shards") or {}
    aggs = result.get("aggregations") or {}
    view = match_data_view(client.data_views(), index)
    kql = query.kql()
    groups = grouper.group(hits) if not correlation else []

    payload: dict[str, Any] = {
        "ok": True,
        "queried_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "tenant": tenant,
        "env": env_name,
        "index": index,
        "space": client.space,
        "application": app,
        "levels": levels,
        "since": gte,
        "until": until,
        "text": text,
        "correlation": correlation,
        "total": total,
        "returned": len(hits),
        "truncated": total > len(hits),
        "shards_total": shards.get("total", 0),
        "kql": kql,
        "discover_url": discover_url(
            host, client.space_prefix, (view or {}).get("id"), kql, gte, until, kibana_version
        ),
        "kibana_version": kibana_version or None,
        "by_level": agg_buckets(aggs, "by_level"),
        "by_logger": agg_buckets(aggs, "by_logger"),
        "by_location": agg_buckets(aggs, "by_location"),
        "timeline": agg_buckets(aggs, "timeline"),
        "groups": groups,
    }
    if correlation:
        payload["events"] = [grouper.event(hit) for hit in hits]
    if agg_note:
        payload["agg_note"] = agg_note
    if shards.get("total", 0) == 0:
        payload["warning"] = (
            f"Index pattern {index} matched 0 shards on this Kibana: "
            "the environment may not live on this host, or the pattern is wrong."
        )

    if args.baseline and not correlation:
        base_gte, base_until = baseline_window(gte, args.baseline)
        try:
            base_result, _ = client.search_with_fallbacks(
                index, lambda kw: query.body(base_gte, base_until, 1000, kw, False, with_aggs=False)
            )
        except SearchError as exc:
            payload["baseline"] = {"error": redact(str(exc))}
        else:
            base_hits = (base_result.get("hits") or {}).get("hits") or []
            base_groups = {g["signature"]: g["count"] for g in grouper.group(base_hits)}
            for group in groups:
                group["baseline_count"] = base_groups.get(group["signature"], 0)
                group["new"] = group["signature"] not in base_groups
            payload["baseline"] = {
                "since": base_gte,
                "until": base_until,
                "total": hits_total(base_result),
                "signatures": len(base_groups),
                "new_signatures": sum(1 for g in groups if g.get("new")),
                "sampled": len(base_hits),
            }

    json.dump(payload, sys.stdout, ensure_ascii=False, indent=2)
    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
    raise SystemExit(main())
