#!/usr/bin/env python3
"""MithTech ERPNext check: a strictly read-only health check of your own ERPNext site.

It reads counts and settings (never business values) for the six areas of MithTech's ERPNext declutter audit
(https://mith.tech/services/erpnext-declutter) and writes one HTML report and one JSON file on your computer.
Nothing is sent anywhere: the only network calls go to the site you name, and they only read.

Two modes:
  API mode (anywhere, Frappe Cloud included; Python 3.9+, standard library only):
      python3 erpnext_check.py https://erp.example.com
      The API key and secret are read from ERPNEXT_API_KEY / ERPNEXT_API_SECRET or asked for (hidden).
  Bench mode (self-hosted; more depth: table sizes, slow-query counter, hand-edited core files):
      cd ~/frappe-bench && env/bin/python /path/to/erpnext_check.py --bench --site erp.example.com

Read-only, by construction:
  - API mode sends only HTTP GET (any other method is refused before it leaves your computer), calls only Frappe's
    read methods, never opens a single document (some mark themselves "seen"), and does not follow redirects.
    Frappe itself rolls back the database transaction of every GET request.
  - Bench mode opens its own database session and makes it READ ONLY (MariaDB refuses any write in it), runs only
    SELECT and SHOW statements, never commits, rolls back at the end, and counts the session's write statements
    (which must be zero). It does not import Frappe, so no Frappe hook, cache write or background job can run.

How to run it, every check, and the API user to make: https://mith.tech/services/erpnext-declutter#run-check
Published only on mith.tech, with its SHA-256 beside it.
"""
from __future__ import annotations

import argparse
import datetime as dt
import getpass
import html
import json
import os
import re
import statistics
import sys
import socket
import subprocess
import time
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple

__version__ = "1.0.0"
SCHEMA = "mithtech.erpnext-check/1"
USER_AGENT = f"mithtech-erpnext-check/{__version__} (read-only)"


# ----------------------------------------------------------------------------------------------------------------
# Errors
# ----------------------------------------------------------------------------------------------------------------


class CheckError(Exception):
    """Stops the whole run (bad URL, wrong key, unreachable site)."""


class ReadOnlyViolation(CheckError):
    """Raised before anything that could write is sent. Never caught by the checks."""


class Unavailable(Exception):
    """One read could not be made (no permission, doctype not on this version, server error). The check that
    asked for it is reported as unavailable; the run goes on."""

    def __init__(self, reason: str, detail: str = ""):
        super().__init__(f"{reason}: {detail}" if detail else reason)
        self.reason = reason  # "permission" | "missing" | "invalid" | "server-error" | "unsupported"
        self.detail = detail


# ----------------------------------------------------------------------------------------------------------------
# Shared reader interface (both modes answer the same questions; the checks never know which mode runs)
# ----------------------------------------------------------------------------------------------------------------

#: Filter operators the readers accept. Filters are lists of [field, op, value].
FILTER_OPS = ("=", "!=", "<", ">", "<=", ">=", "in", "not in", "like", "is")
_FIELD_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
_DOCTYPE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 _\-]{0,139}$")

Filters = Optional[Sequence[Sequence[Any]]]


def check_doctype(doctype: str) -> str:
    if not isinstance(doctype, str) or not _DOCTYPE_RE.match(doctype):
        raise ValueError(f"not a doctype name: {doctype!r}")
    return doctype


def check_field(field: str) -> str:
    if not isinstance(field, str) or not _FIELD_RE.match(field):
        raise ValueError(f"not a field name: {field!r}")
    return field


def check_filters(filters: Filters) -> List[List[Any]]:
    out = []
    for f in filters or []:
        if len(f) != 3:
            raise ValueError(f"filter must be [field, op, value]: {f!r}")
        field, op, value = f
        check_field(field)
        if op not in FILTER_OPS:
            raise ValueError(f"filter operator not allowed: {op!r}")
        if op == "is" and value not in ("set", "not set"):
            raise ValueError("'is' takes 'set' or 'not set'")
        if op in ("in", "not in"):
            value = list(value)
        out.append([field, op, value])
    return out


class Reader:
    """What every check may ask. Implemented by ApiReader (HTTP GET) and BenchReader (read-only SQL)."""

    mode = "base"

    def versions(self) -> Dict[str, str]:  # app -> version
        raise NotImplementedError

    def existing_doctypes(self, names: Iterable[str]) -> set:
        raise NotImplementedError

    def count(self, doctype: str, filters: Filters = None, parent: Optional[str] = None) -> int:
        raise NotImplementedError

    def group_count(
        self, doctype: str, by: str, filters: Filters = None, parent: Optional[str] = None, top: Optional[int] = None
    ) -> List[Tuple[Any, int]]:
        """[(value, count)] most frequent first. `top` limits the groups returned."""
        raise NotImplementedError

    def rows(
        self,
        doctype: str,
        fields: Sequence[str],
        filters: Filters = None,
        parent: Optional[str] = None,
        order_by: Optional[str] = None,
        limit: Optional[int] = None,
    ) -> List[Dict[str, Any]]:
        raise NotImplementedError

    def single_value(self, doctype: str, field: str) -> Any:
        raise NotImplementedError

    def scheduler(self) -> Dict[str, Any]:
        raise NotImplementedError

    def jobs(self) -> Dict[str, Any]:
        """Background queue counts: queued, started, failed, workers."""
        raise NotImplementedError

    def proof(self) -> Dict[str, Any]:
        """Evidence that this run only read."""
        raise NotImplementedError

    def close(self) -> None:
        pass


def frappe_major(versions: Dict[str, str]) -> Optional[int]:
    m = re.match(r"^\D*(\d+)", str(versions.get("frappe", "")))
    return int(m.group(1)) if m else None


# ----------------------------------------------------------------------------------------------------------------
# API mode: HTTP GET only
# ----------------------------------------------------------------------------------------------------------------

LOCAL_HOSTS = ("localhost", "127.0.0.1", "::1")

#: The only server methods API mode calls. All are Frappe read methods; none is whitelisted for POST only.
API_METHODS = (
    "frappe.client.get_list",
    "frappe.client.get_count",
    "frappe.client.get_single_value",
    "frappe.utils.change_log.get_versions",
    "frappe.utils.scheduler.get_scheduler_status",
)


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    """A redirect could carry the API key to another host: never follow one."""

    def redirect_request(self, req, fp, code, msg, headers, newurl):  # noqa: D401
        raise CheckError(
            f"The site answered with a redirect ({code}) to {newurl}. Run the check again with that address."
        )


class GetOnlyTransport:
    """The HTTP layer. Refuses any request whose method is not GET, before anything is sent."""

    def __init__(self, timeout: float = 60.0, opener: Optional[urllib.request.OpenerDirector] = None):
        self.timeout = timeout
        self.opener = opener or urllib.request.build_opener(_NoRedirect())
        self.sent: List[Tuple[str, str]] = []  # (method, path) of every request sent

    def open(self, req: urllib.request.Request):
        method = req.get_method()
        if method != "GET" or req.data is not None:
            raise ReadOnlyViolation(f"refused a {method} request: this tool only sends GET")
        path = urllib.parse.urlsplit(req.full_url).path
        if not any(path == f"/api/method/{m}" for m in API_METHODS):
            raise ReadOnlyViolation(f"refused a call to {path}: not one of the read methods this tool uses")
        self.sent.append((method, path))
        return self.opener.open(req, timeout=self.timeout)


def normalise_site_url(url: str, allow_http: bool = False) -> str:
    url = (url or "").strip()
    if "://" not in url:
        url = "https://" + url
    parts = urllib.parse.urlsplit(url)
    if parts.scheme not in ("http", "https") or not parts.hostname:
        raise CheckError(f"Not a site address: {url!r}. Example: https://erp.example.com")
    if parts.username or parts.password:
        raise CheckError("Put the API key in ERPNEXT_API_KEY / ERPNEXT_API_SECRET, not in the address.")
    if parts.scheme == "http" and parts.hostname not in LOCAL_HOSTS and not allow_http:
        raise CheckError(
            "This address uses http://, which would send your API key unencrypted. Use https://, "
            "or add --allow-http if the site is on your own private network."
        )
    return urllib.parse.urlunsplit((parts.scheme, parts.netloc, "", "", ""))


class ApiReader(Reader):
    mode = "api"

    def __init__(
        self,
        site_url: str,
        api_key: str,
        api_secret: str,
        *,
        timeout: float = 60.0,
        pause: float = 0.0,
        page_size: int = 1000,
        max_rows: int = 200_000,
        allow_http: bool = False,
        transport: Optional[GetOnlyTransport] = None,
        sleep=time.sleep,
    ):
        if not api_key or not api_secret:
            raise CheckError("An API key and secret are needed (ERPNEXT_API_KEY and ERPNEXT_API_SECRET).")
        self.base = normalise_site_url(site_url, allow_http=allow_http)
        self._auth = f"token {api_key}:{api_secret}"
        self.transport = transport or GetOnlyTransport(timeout=timeout)
        self.pause = pause
        self.page_size = page_size
        self.max_rows = max_rows
        self.sleep = sleep
        self.server_errors = 0
        self.unavailable: Dict[str, str] = {}
        self._versions: Optional[Dict[str, str]] = None
        self._major: Optional[int] = None

    # --- HTTP ---------------------------------------------------------------------------------------------------

    def call(self, method: str, **params: Any) -> Any:
        if method not in API_METHODS:
            raise ReadOnlyViolation(f"{method} is not one of the read methods this tool uses")
        query = urllib.parse.urlencode(
            {k: v if isinstance(v, str) else json.dumps(v) for k, v in params.items() if v is not None}
        )
        url = f"{self.base}/api/method/{method}" + (f"?{query}" if query else "")
        headers = {"Authorization": self._auth, "Accept": "application/json", "User-Agent": USER_AGENT}
        for attempt in range(4):
            req = urllib.request.Request(url, headers=headers, method="GET")
            if self.pause:
                self.sleep(self.pause)
            try:
                with self.transport.open(req) as resp:
                    body = resp.read(64 * 1024 * 1024 + 1)
                    if len(body) > 64 * 1024 * 1024:
                        raise Unavailable("invalid", "answer larger than 64 MB")
                    try:
                        return json.loads(body.decode("utf-8")).get("message")
                    except (ValueError, AttributeError):
                        raise CheckError(
                            f"{self.base} did not answer like a Frappe site (no JSON from {method})."
                        ) from None
            except urllib.error.HTTPError as e:
                exc_type, message = _frappe_error(e)
                if e.code == 429 and attempt < 3:
                    wait = _retry_after(e.headers.get("Retry-After"), attempt)
                    self.sleep(wait)
                    continue
                if e.code == 401 or exc_type in ("AuthenticationError", "CSRFTokenError"):
                    raise CheckError(
                        "The site refused the API key and secret (401). Check them, and that the user is enabled."
                    ) from None
                if e.code == 403 or exc_type == "PermissionError":
                    raise Unavailable("permission", message or "this user cannot read it") from None
                if e.code == 404 or exc_type == "DoesNotExistError":
                    raise Unavailable("missing", message or "not found on this site") from None
                if e.code >= 500:
                    # A server error on a GET makes Frappe add one row to its Error Log; never retry one.
                    self.server_errors += 1
                    raise Unavailable("server-error", f"{e.code} {exc_type or ''}".strip()) from None
                raise Unavailable("invalid", f"{e.code} {message or exc_type or ''}".strip()) from None
            except urllib.error.URLError as e:
                raise CheckError(f"Could not reach {self.base}: {e.reason}") from None
        raise Unavailable("server-error", "rate limited (429) four times")

    # --- Reader -------------------------------------------------------------------------------------------------

    def versions(self) -> Dict[str, str]:
        if self._versions is None:
            raw = self.call("frappe.utils.change_log.get_versions") or {}
            self._versions = {
                app: str(v.get("version") or v.get("branch_version") or "")
                for app, v in raw.items()
                if isinstance(v, dict)
            }
            self._major = frappe_major(self._versions)
        return self._versions

    @property
    def major(self) -> Optional[int]:
        if self._versions is None:
            self.versions()
        return self._major

    def _count_field(self) -> Any:
        # Frappe 16 refuses SQL functions written as strings and takes {"COUNT": "*"}; 14 and 15 take the string.
        return {"COUNT": "*", "as": "n"} if (self.major or 16) >= 16 else "count(name) as n"

    def existing_doctypes(self, names: Iterable[str]) -> set:
        names = [check_doctype(n) for n in names]
        found = set()
        for i in range(0, len(names), 100):
            chunk = names[i : i + 100]
            rows = self.call(
                "frappe.client.get_list",
                doctype="DocType",
                fields=["name"],
                filters=[["name", "in", chunk]],
                limit_page_length=len(chunk),
            )
            found.update(r["name"] for r in rows or [])
        return found

    def count(self, doctype: str, filters: Filters = None, parent: Optional[str] = None) -> int:
        check_doctype(doctype)
        if parent:
            # get_count has no parent argument: count the child rows through one grouped list.
            groups = self.group_count(doctype, "parenttype", filters, parent=parent)
            return sum(n for v, n in groups if v == parent)
        return int(self.call("frappe.client.get_count", doctype=doctype, filters=check_filters(filters)) or 0)

    def group_count(
        self, doctype: str, by: str, filters: Filters = None, parent: Optional[str] = None, top: Optional[int] = None
    ) -> List[Tuple[Any, int]]:
        check_doctype(doctype)
        check_field(by)
        flt = check_filters(filters)
        if parent:
            check_doctype(parent)
            flt = flt + [["parenttype", "=", parent]]
        newer = (self.major or 16) >= 16
        out: List[Tuple[Any, int]] = []
        start = 0
        while True:
            page = self.call(
                "frappe.client.get_list",
                doctype=doctype,
                fields=[by, self._count_field()],
                filters=flt,
                group_by=by,
                order_by="n desc" if newer else None,
                limit_start=start,
                limit_page_length=self.page_size,
                parent=parent,
            ) or []
            out.extend((r.get(by), int(r.get("n") or 0)) for r in page)
            start += len(page)
            if len(page) < self.page_size or start >= self.max_rows or (newer and top and start >= top):
                break
        out.sort(key=lambda x: (-x[1], str(x[0])))
        return out[:top] if top else out

    def rows(
        self,
        doctype: str,
        fields: Sequence[str],
        filters: Filters = None,
        parent: Optional[str] = None,
        order_by: Optional[str] = None,
        limit: Optional[int] = None,
    ) -> List[Dict[str, Any]]:
        check_doctype(doctype)
        fields = [check_field(f) for f in fields]
        flt = check_filters(filters)
        if parent:
            check_doctype(parent)
            flt = flt + [["parenttype", "=", parent]]
        if order_by:
            f, _, d = order_by.partition(" ")
            check_field(f)
            if d.lower() not in ("", "asc", "desc"):
                raise ValueError(f"order_by not allowed: {order_by!r}")
        cap = min(limit or self.max_rows, self.max_rows)
        out: List[Dict[str, Any]] = []
        while len(out) < cap:
            size = min(self.page_size, cap - len(out))
            page = self.call(
                "frappe.client.get_list",
                doctype=doctype,
                fields=fields,
                filters=flt,
                order_by=order_by,
                limit_start=len(out),
                limit_page_length=size,
                parent=parent,
            ) or []
            out.extend(page)
            if len(page) < size:
                break
        return out

    def single_value(self, doctype: str, field: str) -> Any:
        return self.call("frappe.client.get_single_value", doctype=check_doctype(doctype), field=check_field(field))

    def scheduler(self) -> Dict[str, Any]:
        out: Dict[str, Any] = {}
        try:
            out["status"] = (self.call("frappe.utils.scheduler.get_scheduler_status") or {}).get("status")
        except Unavailable as e:
            out["status_unavailable"] = e.reason
        return out

    def jobs(self) -> Dict[str, Any]:
        """Counts from Frappe's own read-only views of the queue (RQ Job, RQ Worker): this site's jobs only."""
        out: Dict[str, Any] = {"scope": "this site"}
        for status in ("queued", "started", "failed"):
            # RQ Job is a virtual doctype; its get_count reads filters as [doctype, field, op, value].
            out[status] = int(
                self.call("frappe.client.get_count", doctype="RQ Job", filters=[["RQ Job", "status", "=", status]])
                or 0
            )
        out["workers"] = int(self.call("frappe.client.get_count", doctype="RQ Worker") or 0)
        return out

    def proof(self) -> Dict[str, Any]:
        methods = sorted({m for m, _ in self.transport.sent})
        return {
            "mode": "api",
            "requests": len(self.transport.sent),
            "http_methods": methods,
            "server_methods": sorted({p.rsplit("/", 1)[-1] for _, p in self.transport.sent}),
            "server_errors": self.server_errors,
            "statement": (
                f"{len(self.transport.sent)} requests, all {'/'.join(methods) or 'GET'}, to Frappe read methods only. "
                "Frappe rolls back the database transaction of every GET request."
                + (
                    f" {self.server_errors} request(s) failed on the server; Frappe logs each such failure in its "
                    "Error Log, as it does for any failed page."
                    if self.server_errors
                    else ""
                )
            ),
        }


def _frappe_error(e: urllib.error.HTTPError) -> Tuple[str, str]:
    """(exc_type, first message) from a Frappe error answer; never raises."""
    try:
        body = json.loads(e.read(1024 * 1024).decode("utf-8", "replace"))
    except Exception:
        return "", ""
    exc_type = str(body.get("exc_type") or "")
    message = ""
    try:
        msgs = json.loads(body.get("_server_messages") or "[]")
        if msgs:
            first = json.loads(msgs[0]) if isinstance(msgs[0], str) else msgs[0]
            message = re.sub(r"<[^>]+>", "", str(first.get("message", "")))[:200]
    except Exception:
        pass
    return exc_type, message


def _retry_after(value: Optional[str], attempt: int) -> float:
    try:
        return max(1.0, min(60.0, float(value or 0)))
    except ValueError:
        return float(5 * (attempt + 1))



# ----------------------------------------------------------------------------------------------------------------
# Bench mode: one READ ONLY database session; Frappe is not imported
# ----------------------------------------------------------------------------------------------------------------

#: The only statements bench mode sends that are not SELECT or SHOW: they make the session read-only and end it.
SETUP_STATEMENTS = (
    "SET SESSION TRANSACTION READ ONLY",
    "START TRANSACTION READ ONLY",
    "SET SESSION max_statement_time = 120",
    "ROLLBACK",
)
_SQL_FORBIDDEN = re.compile(
    r";|\binto\s+(out|dump)file\b|\bfor\s+update\b|\block\s+in\s+share\s+mode\b|\bget_lock\s*\(|\bsleep\s*\(|"
    r"\bbenchmark\s*\(|\bload_file\s*\(",
    re.I,
)
#: Session counters that move for reads and for this tool's own setup statements. Any other Com_* counter that
#: moves during the run is reported as a write.
READ_COUNTERS = ("Com_select", "Com_set_option", "Com_begin", "Com_rollback", "Com_empty_query")

#: Apps Frappe publishes, whose files should match their release. Hand edits in these break upgrades.
UPSTREAM_APPS = (
    "frappe", "erpnext", "hrms", "payments", "india_compliance", "lending", "healthcare", "education", "webshop",
    "crm", "helpdesk", "insights", "print_designer", "lms", "wiki", "builder",
)  # fmt: skip


def guard_sql(query: str) -> str:
    """Return the query if it may run in bench mode, else raise ReadOnlyViolation."""
    q = " ".join(str(query).split())
    if q in SETUP_STATEMENTS:
        return q
    head = q.split(" ", 1)[0].upper()
    if head not in ("SELECT", "SHOW"):
        raise ReadOnlyViolation(f"refused a {head} statement: bench mode runs only SELECT and SHOW")
    if _SQL_FORBIDDEN.search(q):
        raise ReadOnlyViolation("refused a statement that could lock, write a file or run more than one statement")
    return q


def find_bench(path: Optional[str]) -> str:
    """The bench folder: the one given, or the current folder (or its parent, when run from sites/)."""
    for cand in [path] if path else [os.getcwd(), os.path.dirname(os.getcwd())]:
        if cand and os.path.isfile(os.path.join(cand, "sites", "common_site_config.json")):
            return os.path.abspath(cand)
    raise CheckError(
        "Bench mode needs the bench folder (the one with sites/ and apps/): run from it, or pass --bench-path."
    )


def site_conf(bench: str, site: str) -> Dict[str, Any]:
    """The site's database settings, merged the way Frappe merges them (site over common, FRAPPE_DB_* over both)."""
    if not site or "/" in site or site.startswith("."):
        raise CheckError("Name the site with --site (the folder name under sites/).")
    sites = os.path.join(bench, "sites")
    path = os.path.join(sites, site, "site_config.json")
    if not os.path.isfile(path):
        raise CheckError(f"No site called {site!r} in {sites}.")
    conf: Dict[str, Any] = {}
    for f in (os.path.join(sites, "common_site_config.json"), path):
        with open(f, encoding="utf-8") as fh:
            conf.update(json.load(fh))
    env = os.environ.get
    conf["db_type"] = env("FRAPPE_DB_TYPE") or conf.get("db_type") or "mariadb"
    conf["db_socket"] = env("FRAPPE_DB_SOCKET") or conf.get("db_socket")
    conf["db_host"] = env("FRAPPE_DB_HOST") or conf.get("db_host") or "127.0.0.1"
    conf["db_port"] = int(env("FRAPPE_DB_PORT") or conf.get("db_port") or 3306)
    conf["db_user"] = env("FRAPPE_DB_USER") or conf.get("db_user") or conf.get("db_name")
    conf["db_password"] = env("FRAPPE_DB_PASSWORD") or conf.get("db_password")
    conf["db_name"] = env("FRAPPE_DB_NAME") or conf.get("db_name") or conf["db_user"]
    return conf


def db_connect(conf: Dict[str, Any]):
    """A plain MariaDB connection with the site's own settings, autocommit off, one statement per call."""
    if conf.get("db_type") != "mariadb":
        raise CheckError("Bench mode reads MariaDB sites. For this site, use API mode.")
    try:
        import pymysql as driver  # type: ignore  # Frappe 14+ ships PyMySQL in the bench
    except ImportError:
        try:
            import MySQLdb as driver  # type: ignore
        except ImportError:
            raise CheckError(
                "No MariaDB driver found. Run this with the bench's Python: env/bin/python erpnext_check.py --bench"
            ) from None
    kw: Dict[str, Any] = dict(user=conf["db_user"], database=conf["db_name"], charset="utf8mb4", autocommit=False)
    if conf.get("db_password"):
        kw["password"] = conf["db_password"]
    if conf.get("db_socket"):
        kw["unix_socket"] = conf["db_socket"]
    else:
        kw["host"], kw["port"] = conf["db_host"], int(conf["db_port"])
    if conf.get("db_ssl_ca"):
        kw["ssl"] = {"ca": conf["db_ssl_ca"]}
    if driver.__name__ == "pymysql":
        kw["local_infile"] = False
        kw["read_timeout"] = 300
    else:
        kw["db"] = kw.pop("database")
        kw["passwd"] = kw.pop("password", "")
    try:
        return driver.connect(**kw)
    except Exception as e:  # never echo the settings: they hold the password
        raise CheckError(f"Could not open the site's database ({e.__class__.__name__}).") from None


def _ident(name: str) -> str:
    return "`" + name + "`"


def _table(doctype: str) -> str:
    return _ident("tab" + check_doctype(doctype))


def _where(filters: Filters, parent: Optional[str]) -> Tuple[str, List[Any]]:
    parts: List[str] = []
    params: List[Any] = []
    for field, op, value in check_filters(filters):
        col = _ident(field)
        if op == "is":
            parts.append(f"({col} IS NOT NULL AND {col} <> '')" if value == "set" else f"({col} IS NULL OR {col} = '')")
        elif op in ("in", "not in"):
            if not value:
                parts.append("1=0" if op == "in" else "1=1")
            else:
                parts.append(f"{col} {op.upper()} ({', '.join(['%s'] * len(value))})")
                params.extend(value)
        else:
            parts.append(f"{col} {op.upper()} %s")
            params.append(value)
    if parent:
        parts.append("`parenttype` = %s")
        params.append(check_doctype(parent))
    return (" WHERE " + " AND ".join(parts)) if parts else "", params


class _RespReader:
    """A minimal Redis client that can only send the read commands below (no library, no handshake extras)."""

    ALLOWED = ("AUTH", "SELECT", "SMEMBERS", "LLEN", "ZCARD", "SCARD")

    def __init__(self, url: str, timeout: float = 10.0, connect=socket.create_connection):
        u = urllib.parse.urlsplit(url)
        if u.scheme != "redis":
            raise Unavailable("unsupported", f"queue address scheme {u.scheme!r}")
        self.sock = connect((u.hostname or "127.0.0.1", u.port or 6379), timeout)
        self.buf = self.sock.makefile("rb")
        if u.password:
            self.cmd("AUTH", *([urllib.parse.unquote(u.username)] if u.username else []), urllib.parse.unquote(u.password))
        db = (u.path or "/0").strip("/") or "0"
        if db != "0":
            self.cmd("SELECT", db)

    def cmd(self, *args: str) -> Any:
        if args[0].upper() not in self.ALLOWED:
            raise ReadOnlyViolation(f"refused Redis command {args[0]}")
        out = b"*%d\r\n" % len(args) + b"".join(
            b"$%d\r\n%s\r\n" % (len(a.encode()), a.encode()) for a in (str(x) for x in args)
        )
        self.sock.sendall(out)
        return self._reply()

    def _reply(self) -> Any:
        line = self.buf.readline().rstrip(b"\r\n")
        kind, rest = line[:1], line[1:]
        if kind == b"+":
            return rest.decode()
        if kind == b"-":
            raise Unavailable("permission" if b"NOAUTH" in rest or b"WRONGPASS" in rest else "invalid", rest.decode())
        if kind == b":":
            return int(rest)
        if kind == b"$":
            n = int(rest)
            if n < 0:
                return None
            data = self.buf.read(n + 2)[:-2]
            return data.decode("utf-8", "replace")
        if kind == b"*":
            n = int(rest)
            return None if n < 0 else [self._reply() for _ in range(n)]
        raise Unavailable("invalid", "unexpected reply from the queue")

    def close(self) -> None:
        try:
            self.buf.close()
            self.sock.close()
        except Exception:
            pass


class BenchReader(Reader):
    mode = "bench"

    def __init__(
        self,
        site: str,
        bench_path: Optional[str] = None,
        *,
        connect=db_connect,
        redis_factory=_RespReader,
        run=subprocess.run,
        conf: Optional[Dict[str, Any]] = None,
    ):
        self.bench = bench_path if conf is not None else find_bench(bench_path)
        self.site = site
        self.conf = conf if conf is not None else site_conf(self.bench, site)
        self.redis_factory = redis_factory
        self.run = run
        self.statements: List[str] = []
        self.conn = connect(self.conf)
        self.cur = self.conn.cursor()
        self._closed = False
        self._open_read_only()

    # --- session --------------------------------------------------------------------------------------------

    def _exec(self, query: str, params: Optional[Sequence[Any]] = None) -> List[Tuple[Any, ...]]:
        q = guard_sql(query)
        self.statements.append(q)
        try:
            self.cur.execute(q, tuple(params) if params else None)
            return list(self.cur.fetchall() or [])
        except ReadOnlyViolation:
            raise
        except Exception as e:
            code = e.args[0] if getattr(e, "args", None) and isinstance(e.args[0], int) else None
            if code == 1792:  # "Cannot execute statement in a READ ONLY transaction": should never happen
                raise ReadOnlyViolation("the database refused a write in the read-only session") from None
            if code == 1146:
                raise Unavailable("missing", "table not on this site") from None
            if code in (1142, 1143, 1227):
                raise Unavailable("permission", "the site's database user cannot read it") from None
            if code == 1969:
                raise Unavailable("timeout", "query stopped after 120 s") from None
            raise Unavailable("invalid", f"{e.__class__.__name__} {code or ''}".strip()) from None

    def _open_read_only(self) -> None:
        self._exec("ROLLBACK")  # nothing is open yet; makes the next line start clean
        self._exec("SET SESSION TRANSACTION READ ONLY")
        try:
            self._exec("SET SESSION max_statement_time = 120")
        except Unavailable:
            pass  # MySQL or old MariaDB: no statement timeout, still read-only
        self._exec("START TRANSACTION READ ONLY")
        ro = None
        for var in ("@@session.transaction_read_only", "@@session.tx_read_only"):
            try:
                ro = self._exec(f"SELECT {var}")[0][0]
                break
            except Unavailable:
                continue
        if str(ro) != "1":
            self.close()
            raise CheckError("Could not make the database session read-only, so the check stopped before reading.")
        self._counters_before = self._counters()

    def _counters(self) -> Dict[str, int]:
        out = {}
        for name, value in self._exec("SHOW SESSION STATUS LIKE 'Com\\_%'"):
            try:
                out[str(name)] = int(value)
            except (TypeError, ValueError):
                pass
        return out

    def close(self) -> None:
        if self._closed:
            return
        self._closed = True
        try:
            self._exec("ROLLBACK")
        finally:
            try:
                self.conn.close()
            except Exception:
                pass

    def proof(self) -> Dict[str, Any]:
        after = self._counters()
        moved = {k: after[k] - self._counters_before.get(k, 0) for k in after}
        moved = {k: v for k, v in moved.items() if v > 0}
        writes = {
            k: v for k, v in moved.items() if k not in READ_COUNTERS and not k.startswith("Com_show_")
        }
        kinds = sorted({s.split(" ", 1)[0].upper() for s in self.statements})
        return {
            "mode": "bench",
            "session": "READ ONLY transaction, rolled back; never committed",
            "statements": len(self.statements),
            "statement_kinds": kinds,
            "write_statements": sum(writes.values()),
            "write_counters": writes,
            "statement": (
                f"{len(self.statements)} statements ({', '.join(kinds)}) in one READ ONLY database session, "
                f"rolled back at the end. MariaDB's own counters for this session show "
                f"{sum(writes.values())} write statements."
            ),
        }

    # --- Reader ---------------------------------------------------------------------------------------------

    def versions(self) -> Dict[str, str]:
        try:
            rows = self._exec(
                "SELECT app_name, app_version FROM `tabInstalled Application` "
                "WHERE parent = 'Installed Applications' ORDER BY idx"
            )
            if rows:
                return {str(a): str(v or "") for a, v in rows}
        except Unavailable:
            pass
        rows = self._exec("SELECT defvalue FROM `tabDefaultValue` WHERE parent = '__default' AND defkey = 'installed_apps'")
        try:
            return {str(a): "" for a in json.loads(rows[0][0])} if rows else {}
        except (ValueError, TypeError):
            return {}

    def existing_doctypes(self, names: Iterable[str]) -> set:
        names = [check_doctype(n) for n in names]
        if not names:
            return set()
        rows = self._exec(f"SELECT name FROM `tabDocType` WHERE name IN ({', '.join(['%s'] * len(names))})", names)
        return {r[0] for r in rows}

    def count(self, doctype: str, filters: Filters = None, parent: Optional[str] = None) -> int:
        where, params = _where(filters, parent)
        return int(self._exec(f"SELECT COUNT(*) FROM {_table(doctype)}{where}", params)[0][0])

    def group_count(
        self, doctype: str, by: str, filters: Filters = None, parent: Optional[str] = None, top: Optional[int] = None
    ) -> List[Tuple[Any, int]]:
        where, params = _where(filters, parent)
        col = _ident(check_field(by))
        limit = f" LIMIT {int(top)}" if top else ""
        rows = self._exec(
            f"SELECT {col}, COUNT(*) AS n FROM {_table(doctype)}{where} GROUP BY {col} ORDER BY n DESC, {col}{limit}",
            params,
        )
        return [(v, int(n)) for v, n in rows]

    def rows(
        self,
        doctype: str,
        fields: Sequence[str],
        filters: Filters = None,
        parent: Optional[str] = None,
        order_by: Optional[str] = None,
        limit: Optional[int] = None,
    ) -> List[Dict[str, Any]]:
        fields = [check_field(f) for f in fields]
        where, params = _where(filters, parent)
        order = ""
        if order_by:
            f, _, d = order_by.partition(" ")
            if d.lower() not in ("", "asc", "desc"):
                raise ValueError(f"order_by not allowed: {order_by!r}")
            order = f" ORDER BY {_ident(check_field(f))} {d.upper()}".rstrip()
        lim = f" LIMIT {int(limit)}" if limit else " LIMIT 200000"
        res = self._exec(f"SELECT {', '.join(_ident(f) for f in fields)} FROM {_table(doctype)}{where}{order}{lim}", params)
        return [dict(zip(fields, r)) for r in res]

    def single_value(self, doctype: str, field: str) -> Any:
        rows = self._exec(
            "SELECT value FROM `tabSingles` WHERE doctype = %s AND field = %s", [check_doctype(doctype), check_field(field)]
        )
        return rows[0][0] if rows else None

    def scheduler(self) -> Dict[str, Any]:
        reasons = []
        if self.conf.get("maintenance_mode"):
            reasons.append("maintenance_mode is on")
        if self.conf.get("pause_scheduler"):
            reasons.append("pause_scheduler is set")
        if self.conf.get("disable_scheduler"):
            reasons.append("disable_scheduler is set")
        if str(self.single_value("System Settings", "enable_scheduler") or "0") in ("0", "None", ""):
            reasons.append("System Settings: scheduler not enabled")
        return {"status": "inactive" if reasons else "active", "reasons": reasons}

    def jobs(self) -> Dict[str, Any]:
        """Queue counts read straight from Redis with read commands only. Bench-wide: every site on this bench."""
        url = self.conf.get("redis_queue")
        if not url:
            raise Unavailable("missing", "redis_queue is not in common_site_config.json")
        if self.conf.get("use_rq_auth"):
            u = urllib.parse.urlsplit(url)
            user = self.conf.get("rq_username")
            pw = self.conf.get("rq_password")
            if not (user and pw):
                raise Unavailable("permission", "the queue needs RQ credentials this tool does not guess")
            url = urllib.parse.urlunsplit(
                (u.scheme, f"{urllib.parse.quote(user)}:{urllib.parse.quote(pw)}@{u.hostname}:{u.port or 6379}", u.path, "", "")
            )
        try:
            r = self.redis_factory(url)
        except Unavailable:
            raise
        except Exception as e:
            raise Unavailable("missing", f"queue not reachable ({e.__class__.__name__})") from None
        try:
            out: Dict[str, Any] = {"scope": "bench (all sites on this bench)", "queued": 0, "started": 0, "failed": 0}
            queues = []
            for key in sorted(r.cmd("SMEMBERS", "rq:queues") or []):
                name = key[len("rq:queue:") :] if key.startswith("rq:queue:") else key
                q = {
                    "queue": name.rsplit(":", 1)[-1],
                    "queued": int(r.cmd("LLEN", key) or 0),
                    "started": int(r.cmd("ZCARD", f"rq:wip:{name}") or 0),
                    "failed": int(r.cmd("ZCARD", f"rq:failed:{name}") or 0),
                }
                queues.append(q)
                for k in ("queued", "started", "failed"):
                    out[k] += q[k]
            out["queues"] = queues
            out["workers"] = int(r.cmd("SCARD", "rq:workers") or 0)
            return out
        finally:
            r.close()

    # --- bench-only depth -----------------------------------------------------------------------------------

    def db_stats(self, top: int = 20) -> Dict[str, Any]:
        tables = self._exec(
            "SELECT table_name, table_rows, data_length, index_length FROM information_schema.TABLES "
            "WHERE table_schema = DATABASE() ORDER BY data_length + index_length DESC"
        )
        total = sum(int(d or 0) + int(i or 0) for _, _, d, i in tables)
        status = dict(
            self._exec("SHOW GLOBAL STATUS WHERE Variable_name IN ('Slow_queries', 'Uptime', 'Questions')")
        )
        variables = dict(
            self._exec(
                "SHOW GLOBAL VARIABLES WHERE Variable_name IN ('innodb_buffer_pool_size', 'slow_query_log', "
                "'long_query_time', 'version', 'max_connections')"
            )
        )
        return {
            "database_bytes": total,
            "tables": len(tables),
            "largest": [
                {"table": str(t), "rows_estimate": int(r or 0), "bytes": int(d or 0) + int(i or 0)}
                for t, r, d, i in tables[:top]
            ],
            "status": {k: str(v) for k, v in status.items()},
            "variables": {k: str(v) for k, v in variables.items()},
        }

    def core_edits(self, apps: Iterable[str]) -> Dict[str, Any]:
        """Uncommitted and unpushed changes in Frappe's published apps, via read-only git commands."""
        env = dict(os.environ, GIT_OPTIONAL_LOCKS="0", GIT_TERMINAL_PROMPT="0")
        out: Dict[str, Any] = {}
        for app in apps:
            path = os.path.join(self.bench, "apps", app)
            if app not in UPSTREAM_APPS or not os.path.isdir(os.path.join(path, ".git")):
                continue

            def git(*args: str) -> Tuple[int, str]:
                p = self.run(
                    ["git", "-c", "core.fsmonitor=false", "--no-optional-locks", "-C", path, *args],
                    capture_output=True, text=True, timeout=120, env=env, check=False,
                )  # fmt: skip
                return p.returncode, (p.stdout or "")

            code, status = git("status", "--porcelain=v1", "--untracked-files=no", "--ignore-submodules")
            if code != 0:
                out[app] = {"unavailable": "git could not read this app folder"}
                continue
            changed = [line[3:] for line in status.splitlines() if len(line) > 3]
            code, ahead = git("rev-list", "--count", "@{upstream}..HEAD")
            out[app] = {
                "changed_files": len(changed),
                "files": changed[:40],
                "local_commits": int(ahead.strip()) if code == 0 and ahead.strip().isdigit() else None,
            }
        return out



# ----------------------------------------------------------------------------------------------------------------
# The checks: the six areas of the declutter audit (src/data/declutter.ts on mith.tech: speed, code, data, stock,
# perms, jobs). Every check returns numbers, names of doctypes/fields/reports/roles/scripts, and never record values.
# ----------------------------------------------------------------------------------------------------------------

AREAS = (
    ("speed", "Speed"),
    ("code", "Upgrades and custom code"),
    ("data", "Data and duplicates"),
    ("stock", "Stock and accounts"),
    ("perms", "Permissions"),
    ("jobs", "Jobs and logs"),
)

#: Field types that hold no value of their own (layout, buttons, child tables).
NO_VALUE_TYPES = {
    "Section Break", "Column Break", "Tab Break", "HTML", "Button", "Heading", "Fold", "Table", "Table MultiSelect",
    "Image",
}  # fmt: skip
#: Drafts older than this many days are listed.
DRAFT_DAYS = 90
#: Masters created before, and unused in, this many days are "unused".
UNUSED_DAYS = 730
DRAFT_DOCTYPES = (
    "Sales Invoice", "Purchase Invoice", "Journal Entry", "Payment Entry", "Stock Entry", "Stock Reconciliation",
    "Delivery Note", "Purchase Receipt",
)  # fmt: skip
LOG_DOCTYPES = (
    "Version", "Error Log", "Activity Log", "Email Queue", "Comment", "Access Log", "Route History",
    "Scheduled Job Log", "Integration Request", "Webhook Request Log", "Deleted Document", "Prepared Report",
)  # fmt: skip
LEDGER_DOCTYPES = ("GL Entry", "Stock Ledger Entry", "Payment Ledger Entry")
#: Roles every Frappe site has; never reported as unused.
AUTOMATIC_ROLES = {"Administrator", "Guest", "All", "Desk User"}


class Ctx:
    """What the checks share: the reader, the site's clock, and rows read once and used by several checks."""

    def __init__(self, reader: Reader, now: Optional[dt.datetime] = None, max_fields: int = 400):
        self.r = reader
        self.versions = reader.versions()
        self.major = frappe_major(self.versions)
        self.max_fields = max_fields
        self.now = now or self._site_now()
        self._cache: Dict[str, Any] = {}

    def _site_now(self) -> dt.datetime:
        try:
            tz = self.r.single_value("System Settings", "time_zone")
            if tz:
                from zoneinfo import ZoneInfo

                return dt.datetime.now(ZoneInfo(str(tz))).replace(tzinfo=None)
        except Exception:
            pass
        return dt.datetime.now()

    def ago(self, days: float = 0, hours: float = 0) -> str:
        return (self.now - dt.timedelta(days=days, hours=hours)).strftime("%Y-%m-%d %H:%M:%S")

    def day(self, days: float) -> str:
        return (self.now - dt.timedelta(days=days)).strftime("%Y-%m-%d")

    def flags(self, *doctypes: str) -> Dict[str, Dict[str, Any]]:
        """{doctype: {issingle, istable, is_virtual}} for the doctypes that exist on this site."""
        known = self._cache.setdefault("doctype_flags", {})
        ask = sorted({check_doctype(d) for d in doctypes if d not in known})
        for i in range(0, len(ask), 100):
            chunk = ask[i : i + 100]
            for d in chunk:
                known[d] = None
            for r in self.rows_optional("DocType", ["name", "issingle", "istable"], ["is_virtual"], filters=[["name", "in", chunk]]):
                known[r["name"]] = {k: int(r.get(k) or 0) for k in ("issingle", "istable", "is_virtual")}
        return {d: known[d] for d in doctypes if known.get(d) is not None}

    def exists(self, *doctypes: str) -> set:
        return set(self.flags(*doctypes))

    def table_parents(self, child: str) -> List[str]:
        """The doctypes that hold `child` as a table (standard and custom table fields)."""

        def find():
            types = ["Table", "Table MultiSelect"]
            std = self.r.rows("DocField", ["parent"], [["fieldtype", "in", types], ["options", "=", child]], parent="DocType")
            cus = [f["dt"] for f in self.custom_fields() if f.get("fieldtype") in types and f.get("options") == child]
            return sorted({r["parent"] for r in std} | set(cus))

        return self.once(f"parents:{child}", find)

    def count_any(self, doctype: str, filters: Filters = None) -> int:
        """Count rows of any stored doctype. Singles and virtual doctypes have no rows to count; a child table is
        counted through its parents in API mode, where Frappe checks permission on the parent."""
        f = self.flags(doctype).get(doctype)
        if not f:
            raise Unavailable("missing", doctype)
        if f["issingle"] or f["is_virtual"]:
            raise Unavailable("unsupported", "single or virtual doctype")
        if f["istable"] and self.r.mode == "api":
            return sum(self.r.count(doctype, filters, parent=p) for p in self.table_parents(doctype))
        return self.r.count(doctype, filters)

    def single_value_safe(self, doctype: str, field: str) -> Any:
        try:
            return self.r.single_value(doctype, field)
        except Unavailable:
            return None

    def once(self, key: str, fn):
        if key not in self._cache:
            try:
                self._cache[key] = (True, fn())
            except Unavailable as e:
                self._cache[key] = (False, e)
        ok, value = self._cache[key]
        if not ok:
            raise value
        return value

    def known_fields(self, doctype: str, candidates: Sequence[str]) -> List[str]:
        """The candidates this site's version of `doctype` has (asked of DocField, so no query names a missing one)."""
        if not candidates:
            return []

        def find():
            rows = self.r.rows(
                "DocField", ["fieldname"], [["parent", "=", doctype], ["fieldname", "in", list(candidates)]], parent="DocType"
            )
            return {r["fieldname"] for r in rows}

        try:
            have = self.once(f"fields:{doctype}:{','.join(candidates)}", find)
        except Unavailable:
            return []
        return [f for f in candidates if f in have]

    def rows_optional(self, doctype: str, fields: Sequence[str], optional: Sequence[str], **kw) -> List[Dict[str, Any]]:
        """Rows with the `optional` fields this version has (older Frappe lacks some)."""
        extra = self.known_fields(doctype, optional)
        try:
            return self.r.rows(doctype, list(fields) + extra, **kw)
        except Unavailable as e:
            if e.reason != "invalid" or not extra:  # bench mode: a column the site has not migrated yet
                raise
            return self.r.rows(doctype, list(fields), **kw)

    # rows used by more than one check
    def custom_fields(self) -> List[Dict[str, Any]]:
        return self.once(
            "custom_fields",
            lambda: self.rows_optional(
                "Custom Field", ["dt", "fieldname", "fieldtype", "module", "options"], ["is_system_generated", "is_virtual"]
            ),
        )

    def modules(self) -> Dict[str, str]:
        return self.once(
            "modules", lambda: {m["name"]: m.get("app_name") or "" for m in self.r.rows("Module Def", ["name", "app_name"])}
        )

    def error_titles(self, days: int = 30) -> List[Dict[str, Any]]:
        return self.once(
            f"errors{days}",
            lambda: self.r.rows(
                "Error Log", ["method", "reference_doctype", "reference_name"], [["creation", ">=", self.ago(days)]]
            ),
        )


def result(
    area: str, cid: str, title: str, status: str, summary: str, metrics=None, items=None, note: str = ""
) -> Dict[str, Any]:
    return {
        "id": f"{area}.{cid}",
        "area": area,
        "title": title,
        "status": status,  # "look" | "ok" | "info" | "unavailable" | "error"
        "summary": summary,
        "metrics": metrics or {},
        "items": items or [],
        "note": note,
    }


def n(x: int, one: str, many: Optional[str] = None) -> str:
    return f"{x:,} {one if x == 1 else (many or one + 's')}"


def pct(a: int, b: int) -> float:
    return round(100.0 * a / b, 1) if b else 0.0


_TITLE_MASKS = (
    (re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+"), "…"),  # email addresses
    (re.compile(r"'[^']*'|\"[^\"]*\""), "…"),  # quoted values
    (re.compile(r"\bnew-[a-z0-9-]+\b"), "…"),  # unsaved document names
    (re.compile(r"\b(?=[\w/-]*[A-Z0-9])(?=[\w/-]*-)[\w/]+(?:-[\w/]+)+\b"), "…"),  # document codes: ACC-SINV-2026-00012
    (re.compile(r"\d+"), "#"),
)


def mask_title(title: Any, limit: int = 90) -> str:
    """An Error Log title with record names, values and numbers masked, so it says what failed, not for whom."""
    t = " ".join(str(title or "").split())
    for rx, rep in _TITLE_MASKS:
        t = rx.sub(rep, t)
    return t if len(t) <= limit else t[: limit - 1] + "…"


def parse_dt(value: Any) -> Optional[dt.datetime]:
    if not value:
        return None
    if isinstance(value, dt.datetime):
        return value
    try:
        return dt.datetime.fromisoformat(str(value)[:26])
    except ValueError:
        return None


# --- Speed ------------------------------------------------------------------------------------------------------


def check_prepared_reports(c: Ctx):
    rows = c.rows_optional(
        "Prepared Report", ["report_name", "status", "creation", "modified"], ["queued_at", "report_end_time"],
        filters=[["creation", ">=", c.ago(90)]], order_by="creation desc", limit=20000,
    )  # fmt: skip
    by: Dict[str, Dict[str, Any]] = {}
    stuck = 0
    for r in rows:
        b = by.setdefault(str(r.get("report_name")), {"runs": 0, "errors": 0, "seconds": []})
        b["runs"] += 1
        if r.get("status") == "Error":
            b["errors"] += 1
        start = parse_dt(r.get("queued_at")) or parse_dt(r.get("creation"))
        end = parse_dt(r.get("report_end_time")) or (
            parse_dt(r.get("modified")) if r.get("status") in ("Completed", "Error") else None
        )
        if start and end and end >= start:
            b["seconds"].append((end - start).total_seconds())
        if r.get("status") in ("Queued", "Started") and start and start < c.now - dt.timedelta(hours=1):
            stuck += 1
    items = []
    for name, b in by.items():
        secs = b["seconds"]
        items.append(
            {
                "report": name,
                "runs": b["runs"],
                "errors": b["errors"],
                "median_s": round(statistics.median(secs)) if secs else None,
                "max_s": round(max(secs)) if secs else None,
            }
        )
    items.sort(key=lambda i: (-(i["max_s"] or 0), -i["runs"]))
    slow = [i for i in items if (i["max_s"] or 0) >= 300]
    errors = sum(i["errors"] for i in items)
    look = bool(slow or errors or stuck)
    summary = (
        f"{n(len(rows), 'prepared report run')} in 90 days across {n(len(items), 'report')}; "
        f"{n(len(slow), 'report')} took 5 minutes or more, {n(errors, 'run')} failed, {stuck} stuck in the queue."
        if rows
        else "No prepared reports in 90 days: either reports are fast, or none is set to run in the background."
    )
    return result(
        "speed", "prepared_reports", "Prepared (background) reports", "look" if look else ("ok" if rows else "info"),
        summary, {"runs_90d": len(rows), "reports": len(items), "slow_reports": len(slow), "failed_runs": errors,
                  "stuck": stuck}, items[:15],
        "A prepared report runs in the background because it is too slow for the page. Time = queued to finished.",
    )  # fmt: skip


def check_reports(c: Ctx):
    rows = c.r.rows("Report", ["name", "report_type", "is_standard", "disabled", "prepared_report", "ref_doctype"])
    custom = [r for r in rows if r.get("is_standard") == "No"]
    by_type: Dict[str, int] = {}
    for r in custom:
        by_type[r.get("report_type") or "?"] = by_type.get(r.get("report_type") or "?", 0) + 1
    raw_sql = [r for r in custom if r.get("report_type") in ("Query Report", "Script Report") and not r.get("disabled")]
    prepared = [r for r in rows if r.get("prepared_report")]
    items = [{"report": r["name"], "type": r.get("report_type"), "on": r.get("ref_doctype")} for r in raw_sql[:30]]
    return result(
        "speed", "custom_reports", "Custom reports", "info",
        f"{n(len(custom), 'custom report')} ({', '.join(f'{v} {k}' for k, v in sorted(by_type.items())) or 'none'}); "
        f"{n(len(raw_sql), 'custom query or script report')} enabled; {n(len(prepared), 'report')} set to run in the background.",
        {"custom": len(custom), "custom_query_or_script": len(raw_sql), "prepared": len(prepared), "by_type": by_type},
        items, "Custom query and script reports run their own SQL: the first place to look when a report is slow.",
    )  # fmt: skip


def check_ledgers(c: Ctx):
    have = c.exists(*LEDGER_DOCTYPES)
    counts = {d: c.r.count(d) for d in LEDGER_DOCTYPES if d in have}
    total = sum(counts.values())
    return result(
        "speed", "ledger_size", "Ledger size", "look" if total >= 1_000_000 else "info",
        "; ".join(f"{d}: {v:,} rows" for d, v in counts.items()) + "."
        + (" A ledger past a million rows needs its reports indexed or prepared." if total >= 1_000_000 else ""),
        counts, note="Reports that read a whole ledger slow down as it grows (Frappe measured over two minutes "
        "for Stock Balance on about a million rows).",
    )  # fmt: skip


def check_database(c: Ctx):
    if not hasattr(c.r, "db_stats"):
        raise Unavailable("unsupported", "bench mode only (table sizes and database settings)")
    s = c.r.db_stats()  # type: ignore[attr-defined]
    v, st = s["variables"], s["status"]
    pool = int(v.get("innodb_buffer_pool_size") or 0)
    size = int(s["database_bytes"])
    mb = lambda b: f"{b / 1048576:,.0f} MB"  # noqa: E731
    flags = []
    if pool and size and pool < size:
        flags.append(f"the buffer pool ({mb(pool)}) is smaller than this database ({mb(size)})")
    if str(v.get("slow_query_log", "")).upper() in ("OFF", "0"):
        flags.append("the slow query log is off")
    items = [{"table": t["table"], "rows (estimate)": t["rows_estimate"], "size": mb(t["bytes"])} for t in s["largest"]]
    return result(
        "speed", "database", "Database size and settings", "look" if flags else "ok",
        f"{mb(size)} in {s['tables']:,} tables; buffer pool {mb(pool)}; {st.get('Slow_queries', '?')} slow quer{'y' if str(st.get('Slow_queries')) == '1' else 'ies'} "
        f"since the server started ({n(int(st.get('Uptime', 0) or 0) // 86400, 'day')} ago)."
        + (" Worth a look: " + "; ".join(flags) + "." if flags else ""),
        {"database_bytes": size, "buffer_pool_bytes": pool, "slow_queries": st.get("Slow_queries"),
         "uptime_s": st.get("Uptime"), "slow_query_log": v.get("slow_query_log"),
         "long_query_time": v.get("long_query_time"), "server_version": v.get("version")}, items,
        "Bench mode. Table sizes are MariaDB's estimates. The server-wide counters cover every site on it.",
    )  # fmt: skip


# --- Upgrades and custom code -----------------------------------------------------------------------------------


def _orphan(module: Optional[str], modules: Dict[str, str], apps: set) -> Optional[str]:
    if not module:
        return None
    if module not in modules:
        return f"module {module} (gone)"
    app = modules[module]
    if app and app not in apps:
        return f"app {app} (not installed)"
    return None


def check_custom_fields(c: Ctx):
    rows = c.custom_fields()
    modules, apps = c.modules(), set(c.versions)
    dts = sorted({r["dt"] for r in rows if r.get("dt")})
    live = c.exists(*dts) if dts else set()
    by_dt: Dict[str, int] = {}
    orphans: Dict[str, int] = {}
    on_missing = 0
    for r in rows:
        by_dt[r["dt"]] = by_dt.get(r["dt"], 0) + 1
        why = _orphan(r.get("module"), modules, apps)
        if r.get("dt") not in live:
            on_missing += 1
            why = why or f"doctype {r.get('dt')} (gone)"
        if why:
            orphans[why] = orphans.get(why, 0) + 1
    by_app = sum(1 for r in rows if r.get("is_system_generated"))
    n_orphans = sum(orphans.values())
    items = [{"left by": k, "fields": v} for k, v in sorted(orphans.items(), key=lambda x: -x[1])]
    items += [{"doctype": d, "custom fields": v} for d, v in sorted(by_dt.items(), key=lambda x: -x[1])[:15]]
    return result(
        "code", "custom_fields", "Custom fields", "look" if n_orphans else "ok",
        f"{n(len(rows), 'custom field')} on {n(len(by_dt), 'doctype')}"
        + (f" ({by_app:,} added by apps, {len(rows) - by_app:,} by hand)" if any("is_system_generated" in r for r in rows) else "")
        + f"; {n(n_orphans, 'field')} left behind by an app, module or doctype that is gone.",
        {"total": len(rows), "doctypes": len(by_dt), "added_by_apps": by_app, "orphaned": n_orphans,
         "on_missing_doctypes": on_missing}, items,
        "Orphaned = its module belongs to an app no longer installed, or its module or doctype no longer exists.",
    )  # fmt: skip


def check_property_setters(c: Ctx):
    rows = c.rows_optional("Property Setter", ["doc_type", "property", "module"], ["is_system_generated"])
    modules, apps = c.modules(), set(c.versions)
    by_dt: Dict[str, int] = {}
    orphaned = 0
    for r in rows:
        by_dt[r.get("doc_type")] = by_dt.get(r.get("doc_type"), 0) + 1
        if _orphan(r.get("module"), modules, apps):
            orphaned += 1
    by_hand = sum(1 for r in rows if "is_system_generated" in r and not r.get("is_system_generated"))
    items = [{"doctype": d, "changes": v} for d, v in sorted(by_dt.items(), key=lambda x: -x[1])[:15]]
    return result(
        "code", "property_setters", "Form changes (Customize Form)", "look" if orphaned else "info",
        f"{n(len(rows), 'change')} to standard forms on {n(len(by_dt), 'doctype')}"
        + (f" ({by_hand:,} made by hand)" if by_hand else "")
        + (f"; {orphaned:,} left by an app that is gone." if orphaned else "."),
        {"total": len(rows), "doctypes": len(by_dt), "by_hand": by_hand, "orphaned": orphaned}, items,
        "Every Customize Form edit is stored as a property setter and must survive each upgrade.",
    )  # fmt: skip


def check_scripts(c: Ctx):
    server_note = ""
    try:
        server = c.r.rows("Server Script", ["name", "script_type", "reference_doctype", "disabled"])
    except Unavailable as e:
        if e.reason != "permission":
            raise
        server, server_note = [], " Server scripts not readable by this user (they need the Script Manager role)."
    client = c.r.rows("Client Script", ["name", "dt", "enabled"])
    names = {s["name"] for s in server}
    hits: Dict[str, int] = {}
    try:
        for e in c.error_titles(30):
            ref = e.get("reference_name") if e.get("reference_doctype") == "Server Script" else None
            title = str(e.get("method") or "")
            for name in names:
                if name == ref or (len(name) >= 4 and name in title):
                    hits[name] = hits.get(name, 0) + 1
    except Unavailable:
        pass
    s_on = [s for s in server if not s.get("disabled")]
    c_on = [s for s in client if s.get("enabled")]
    off = (len(server) - len(s_on)) + (len(client) - len(c_on))
    by_type: Dict[str, int] = {}
    for s in s_on:
        by_type[s.get("script_type") or "?"] = by_type.get(s.get("script_type") or "?", 0) + 1
    items = [{"server script": k, "errors (30 days)": v} for k, v in sorted(hits.items(), key=lambda x: -x[1])]
    return result(
        "code", "scripts", "Server and client scripts", "look" if hits else "info",
        f"{n(len(s_on), 'server script')} on ({', '.join(f'{v} {k}' for k, v in sorted(by_type.items())) or 'none'}), "
        f"{n(len(c_on), 'client script')} on, {n(off, 'script')} switched off"
        + (f"; {n(len(hits), 'server script')} named in errors in the last 30 days." if hits else ".")
        + server_note,
        {"server_on": len(s_on), "client_on": len(c_on), "off": off, "server_by_type": by_type,
         "with_errors_30d": len(hits)}, items,
        "Scripts live in the database, outside version control: each one is code an upgrade can break.",
    )  # fmt: skip


def check_print_formats(c: Ctx):
    rows = c.rows_optional(
        "Print Format", ["name", "doc_type", "disabled", "print_format_type", "custom_format"],
        ["print_format_builder", "print_format_builder_beta", "raw_printing"], filters=[["standard", "=", "No"]],
    )  # fmt: skip
    on = [r for r in rows if not r.get("disabled")]
    html = [r for r in on if r.get("custom_format") and (r.get("print_format_type") or "Jinja") == "Jinja"]
    by_dt: Dict[str, int] = {}
    for r in on:
        by_dt[r.get("doc_type")] = by_dt.get(r.get("doc_type"), 0) + 1
    items = [{"doctype": d, "custom print formats": v} for d, v in sorted(by_dt.items(), key=lambda x: -x[1])[:15]]
    return result(
        "code", "print_formats", "Custom print formats", "info",
        f"{n(len(on), 'custom print format')} in use ({len(html):,} hand-written HTML/Jinja), {len(rows) - len(on):,} switched off.",
        {"in_use": len(on), "html_jinja": len(html), "off": len(rows) - len(on)}, items,
        "Hand-written print formats are the ones that break when an upgrade changes a field or a filter.",
    )  # fmt: skip


def check_core_files(c: Ctx):
    if not hasattr(c.r, "core_edits"):
        raise Unavailable("unsupported", "bench mode only (reads the app folders on the server)")
    edits = c.r.core_edits(c.versions)  # type: ignore[attr-defined]
    changed = {a: e for a, e in edits.items() if e.get("changed_files") or e.get("local_commits")}
    items = []
    for app, e in edits.items():
        items.append(
            {"app": app, "files changed": e.get("changed_files", "?"), "local commits": e.get("local_commits"),
             "files": ", ".join(e.get("files", [])[:8])}  # fmt: skip
        )
    return result(
        "code", "core_files", "Hand-edited core files", "look" if changed else "ok",
        (f"{n(len(changed), 'published app')} edited in place: " + ", ".join(sorted(changed)) + ".")
        if changed
        else f"No uncommitted or local changes in {n(len(edits), 'published app')} ({', '.join(sorted(edits))}).",
        {"apps_checked": len(edits), "apps_edited": len(changed)}, items,
        "git status and local commits in Frappe's published apps. Edits there are lost or block the next update.",
    )  # fmt: skip


# --- Data and duplicates ----------------------------------------------------------------------------------------


def check_fill_rates(c: Ctx):
    fields = [
        f for f in c.custom_fields()
        if f.get("fieldtype") not in NO_VALUE_TYPES and not f.get("is_virtual") and f.get("dt") and f.get("fieldname")
    ]  # fmt: skip
    live = c.exists(*sorted({f["dt"] for f in fields})) if fields else set()
    totals: Dict[str, int] = {}
    unreadable = set()
    for d in sorted({f["dt"] for f in fields if f["dt"] in live}):
        try:
            totals[d] = c.count_any(d)
        except Unavailable as e:
            if e.reason == "permission":
                unreadable.add(d)
            elif e.reason not in ("invalid", "missing", "unsupported"):
                raise
    # Measure the fields of doctypes that have records, biggest doctypes first, up to the limit.
    todo = sorted((f for f in fields if totals.get(f["dt"])), key=lambda f: (-totals[f["dt"]], f["dt"], f["fieldname"]))
    skipped = max(0, len(todo) - c.max_fields)
    items = []
    never = rarely = 0
    for f in todo[: c.max_fields]:
        d, total = f["dt"], totals[f["dt"]]
        flt = [[f["fieldname"], "=", 1]] if f.get("fieldtype") == "Check" else [[f["fieldname"], "is", "set"]]
        try:
            filled = c.count_any(d, flt)
        except Unavailable as e:
            if e.reason in ("invalid", "missing", "unsupported", "permission"):
                continue
            raise
        rate = pct(filled, total)
        if total >= 50 and filled == 0:
            never += 1
        elif total >= 50 and rate < 5:
            rarely += 1
        items.append({"doctype": d, "field": f["fieldname"], "type": f.get("fieldtype"), "records": total,
                      "filled": filled, "fill %": rate})  # fmt: skip
    items.sort(key=lambda i: (i["fill %"], -i["records"]))
    measured = len(items)
    return result(
        "data", "fill_rates", "Custom fields nobody fills", "look" if never else ("info" if measured else "ok"),
        f"Of {n(measured, 'custom field')} measured, {never:,} were never filled and {rarely:,} are filled on under 5% "
        f"of records (counting doctypes with 50 records or more)."
        + (f" {skipped:,} more fields not measured (limit {c.max_fields}, --max-fields)." if skipped else "")
        + (f" Not readable by this user: {', '.join(sorted(unreadable))}." if unreadable else ""),
        {"measured": measured, "never_filled": never, "rarely_filled": rarely, "not_measured": skipped,
         "unreadable_doctypes": sorted(unreadable)}, items[:40],
        "Fill = share of records where the field has a value (a ticked box for checkboxes; 0 counts as empty). "
        "Fields on doctypes with no records are left out.",
    )  # fmt: skip


_SUFFIXES = re.compile(r"(privatelimited|pvtltd|limited|ltd|llp|inc|llc|company|co|corp|corporation|gmbh)$")


def norm_name(name: Any) -> str:
    s = re.sub(r"[^0-9a-z]+", "", str(name or "").casefold())
    prev = None
    while s and s != prev:
        prev, s = s, _SUFFIXES.sub("", s)
    return s


def _dupe_groups(values: Iterable[Any], key) -> Tuple[int, int]:
    seen: Dict[str, int] = {}
    for v in values:
        k = key(v)
        if k:
            seen[k] = seen.get(k, 0) + 1
    groups = [x for x in seen.values() if x > 1]
    return len(groups), sum(groups)


def check_duplicates(c: Ctx):
    items = []
    unreadable = []
    total_groups = 0
    plan = (
        ("Customer", "customer_name", "tax_id", []),
        ("Supplier", "supplier_name", "tax_id", []),
        ("Item", "item_name", None, [["variant_of", "is", "not set"]]),
    )
    for doctype, name_f, tax_f, extra in plan:
        fields = [name_f] + ([tax_f] if tax_f else [])
        try:
            rows = c.r.rows(doctype, fields, [["disabled", "=", 0]] + extra)
        except Unavailable as e:
            if e.reason == "permission":
                unreadable.append(doctype)
                continue
            raise
        g, recs = _dupe_groups((r.get(name_f) for r in rows), norm_name)
        tg, trecs = (
            _dupe_groups((r.get(tax_f) for r in rows), lambda v: re.sub(r"\s+", "", str(v or "")).upper())
            if tax_f
            else (0, 0)
        )
        total_groups += g + tg
        items.append({"master": doctype, "active records": len(rows), "same-name groups": g, "records in them": recs,
                      "same-tax-ID groups": tg if tax_f else None, "records with shared tax ID": trecs if tax_f else None})  # fmt: skip
    return result(
        "data", "duplicates", "Duplicate customers, suppliers and items", "look" if total_groups else "ok",
        "; ".join(
            f"{i['master']}: {n(i['same-name groups'], 'name')} shared by {n(i['records in them'], 'record')}"
            + (f", {n(i['same-tax-ID groups'], 'shared tax ID')}" if i["same-tax-ID groups"] is not None else "")
            for i in items
        ) + "." + (f" Not readable by this user: {', '.join(unreadable)}." if unreadable else ""),
        {"groups": total_groups, "unreadable": unreadable}, items,
        "Names compared without case, spaces, punctuation or endings like Pvt Ltd. Only counts leave this computer "
        "if you share the report; the names themselves are not written anywhere.",
    )  # fmt: skip


def check_unused_masters(c: Ctx):
    cutoff = c.day(UNUSED_DAYS)
    items, unreadable = [], []
    plan = (
        ("Customer", [["disabled", "=", 0]], "Sales Invoice", "customer", [["docstatus", "=", 1]]),
        ("Supplier", [["disabled", "=", 0]], "Purchase Invoice", "supplier", [["docstatus", "=", 1]]),
        ("Item", [["disabled", "=", 0], ["is_stock_item", "=", 1], ["has_variants", "=", 0]],
         "Stock Ledger Entry", "item_code", [["is_cancelled", "=", 0]]),
    )  # fmt: skip
    worst = 0.0
    for master, mflt, txn, link, tflt in plan:
        try:
            old = c.r.rows(master, ["name"], mflt + [["creation", "<", cutoff]])
            used = {v for v, _ in c.r.group_count(txn, link, tflt + [["posting_date", ">=", cutoff]])}
        except Unavailable as e:
            if e.reason == "permission":
                unreadable.append(master)
                continue
            raise
        unused = sum(1 for r in old if r["name"] not in used)
        share = pct(unused, len(old))
        worst = max(worst, share)
        items.append({"master": master, "older than 2 years": len(old), "no use in 2 years": unused, "share %": share,
                      "use = ": f"a submitted {txn}" if txn != "Stock Ledger Entry" else "a stock movement"})  # fmt: skip
    return result(
        "data", "unused_masters", "Masters nobody uses", "look" if worst >= 20 else "info",
        "; ".join(f"{i['master']}: {i['no use in 2 years']:,} of {i['older than 2 years']:,} older records unused ({i['share %']}%)" for i in items)
        + "." + (f" Not readable by this user: {', '.join(unreadable)}." if unreadable else ""),
        {"unused_share_max": worst, "unreadable": unreadable}, items,
        "Enabled masters created over 2 years ago with no invoice (customers, suppliers) or stock movement (stock "
        "items) in the last 2 years. Candidates to disable, not to delete.",
    )  # fmt: skip


# --- Stock and accounts -----------------------------------------------------------------------------------------


def check_reposts(c: Ctx):
    if not c.exists("Repost Item Valuation"):
        raise Unavailable("missing", "Repost Item Valuation is not on this site")
    by_status = dict(c.r.group_count("Repost Item Valuation", "status", [["docstatus", "=", 1]]))
    stuck = c.r.count(
        "Repost Item Valuation",
        [["docstatus", "=", 1], ["status", "in", ["Queued", "In Progress"]], ["modified", "<", c.ago(1)]],
    )
    failed_90 = c.r.count("Repost Item Valuation", [["status", "=", "Failed"], ["modified", ">=", c.ago(90)]])
    look = bool(stuck or failed_90)
    return result(
        "stock", "reposts", "Repost Item Valuation queue", "look" if look else "ok",
        f"{n(stuck, 'repost')} queued or running for over a day; {failed_90:,} failed in 90 days."
        + (" By status: " + ", ".join(f"{k} {v:,}" for k, v in sorted(by_status.items(), key=lambda x: str(x[0]))) + "." if by_status else ""),
        {"stuck_over_1_day": stuck, "failed_90d": failed_90, "by_status": {str(k): v for k, v in by_status.items()}},
        note="A stuck repost leaves stock values and the ledger out of date until it finishes.",
    )  # fmt: skip


def check_old_drafts(c: Ctx):
    have = c.exists(*DRAFT_DOCTYPES)
    items, unreadable = [], []
    for d in DRAFT_DOCTYPES:
        if d not in have:
            continue
        try:
            k = c.r.count(d, [["docstatus", "=", 0], ["creation", "<", c.ago(DRAFT_DAYS)]])
        except Unavailable as e:
            if e.reason == "permission":
                unreadable.append(d)
                continue
            raise
        if k:
            items.append({"doctype": d, "drafts older than 90 days": k})
    total = sum(i["drafts older than 90 days"] for i in items)
    return result(
        "stock", "old_drafts", "Old draft entries", "look" if total else "ok",
        f"{n(total, 'draft')} older than {DRAFT_DAYS} days across stock and accounting entries."
        + (f" Not readable by this user: {', '.join(unreadable)}." if unreadable else ""),
        {"total": total, "unreadable": unreadable}, items,
        "A backdated draft submitted months later reposts stock and changes closed figures.",
    )  # fmt: skip


def check_ledger_health(c: Ctx):
    flags, notes, metrics = [], [], {}
    neg = c.single_value_safe("Stock Settings", "allow_negative_stock")
    metrics["allow_negative_stock"] = neg
    if str(neg) == "1":
        flags.append("negative stock is allowed (valuation can drift)")
    if c.exists("Ledger Health"):
        on = c.single_value_safe("Ledger Health Monitor", "enable_health_monitor")
        metrics["health_monitor_on"] = on
        dc = c.r.count("Ledger Health", [["debit_credit_mismatch", "=", 1]])
        gp = c.r.count("Ledger Health", [["general_and_payment_ledger_mismatch", "=", 1]])
        metrics.update(debit_credit_mismatch=dc, general_payment_mismatch=gp)
        if dc or gp:
            flags.append(f"Ledger Health lists {dc:,} debit/credit and {gp:,} general/payment ledger mismatches")
        if str(on) != "1":
            notes.append("ERPNext's Ledger Health Monitor is off, so it lists nothing")
    else:
        metrics["health_monitor"] = "not on this version"
    return result(
        "stock", "ledger_health", "Ledger health signals", "look" if flags else "ok",
        (("Worth a look: " + "; ".join(flags) + ".") if flags else "Negative stock is off and no ledger mismatches are listed.")
        + ("" if not notes else " " + "; ".join(notes) + "."),
        metrics, note="Read from Stock Settings and ERPNext's own Ledger Health records; the audit checks the ledger itself.",
    )  # fmt: skip


# --- Permissions ------------------------------------------------------------------------------------------------


def check_roles(c: Ctx):
    users = c.rows_optional("User", ["name", "enabled"], ["user_type"])
    active = {u["name"] for u in users if u.get("enabled") and u.get("user_type", "System User") == "System User"}
    active.discard("Guest")
    has = c.r.rows("Has Role", ["parent", "role"], parent="User")
    roles = c.rows_optional("Role", ["name", "disabled"], ["is_custom"])
    holders: Dict[str, int] = {}
    for h in has:
        if h.get("parent") in active:
            holders[h["role"]] = holders.get(h["role"], 0) + 1
    sysman = holders.get("System Manager", 0)
    custom = [r for r in roles if r.get("is_custom") and not r.get("disabled")]
    unused = sorted(
        r["name"] for r in roles if not r.get("disabled") and r["name"] not in AUTOMATIC_ROLES and not holders.get(r["name"])
    )
    unused_custom = [r["name"] for r in custom if r["name"] in unused]
    too_many_admins = sysman > max(3, len(active) // 5)
    look = too_many_admins or bool(unused_custom)
    items = [{"role": r, "enabled users": v} for r, v in sorted(holders.items(), key=lambda x: -x[1])[:20]]
    items += [{"unused custom role": r} for r in unused_custom[:30]]
    return result(
        "perms", "roles", "Roles and who holds them", "look" if look else "ok",
        f"{n(len(active), 'enabled system user')}; {sysman:,} hold System Manager; {n(len(custom), 'custom role')}, "
        f"{len(unused_custom):,} held by nobody.",
        {"system_users": len(active), "system_managers": sysman, "custom_roles": len(custom),
         "unused_custom_roles": len(unused_custom), "unused_roles": len(unused)}, items,
        "Counts only; no user is named. In API mode Frappe may hide Administrator from the count.",
    )  # fmt: skip


def check_user_permissions(c: Ctx):
    total = c.r.count("User Permission")
    per_user = [k for _, k in c.r.group_count("User Permission", "user")]
    by_dt = c.r.group_count("User Permission", "allow", top=15)
    to_all = c.r.count("User Permission", [["apply_to_all_doctypes", "=", 1]])
    heavy = sum(1 for k in per_user if k > 100)
    items = [{"restricts by": d, "rows": k} for d, k in by_dt]
    return result(
        "perms", "user_permissions", "User permissions", "look" if heavy else ("info" if total else "ok"),
        f"{n(total, 'user permission row')} for {n(len(per_user), 'user')}; most for one user: {max(per_user or [0]):,}; "
        f"{to_all:,} apply to every doctype." + (f" {n(heavy, 'user')} with over 100 rows." if heavy else ""),
        {"rows": total, "users": len(per_user), "max_per_user": max(per_user or [0]), "apply_to_all": to_all,
         "users_over_100": heavy}, items,
        "Every user permission adds a condition to that user's queries; many rows slow lists and reports, and "
        "strict settings can hide whole document types.",
    )  # fmt: skip


def check_custom_perms(c: Ctx):
    groups = c.r.group_count("Custom DocPerm", "parent")
    total = sum(k for _, k in groups)
    items = [{"doctype": d, "custom permission rules": k} for d, k in groups[:15]]
    return result(
        "perms", "custom_perms", "Changed role permissions", "info" if total else "ok",
        f"{n(total, 'custom permission rule')} on {n(len(groups), 'doctype')} (Role Permission Manager edits).",
        {"rules": total, "doctypes": len(groups)}, items,
        "Once a doctype's permissions are edited, its standard rules stop applying: roles copied and widened over "
        "time show up here.",
    )  # fmt: skip


# --- Jobs and logs ----------------------------------------------------------------------------------------------


def check_errors(c: Ctx):
    total = c.r.count("Error Log")
    last30 = c.error_titles(30)
    day = c.r.count("Error Log", [["creation", ">=", c.ago(1)]])
    groups: Dict[str, int] = {}
    for e in last30:
        t = mask_title(e.get("method"))
        groups[t] = groups.get(t, 0) + 1
    top = sorted(groups.items(), key=lambda x: -x[1])[:10]
    loud = top[0][1] if top else 0
    look = len(last30) > 300 or loud >= 100
    return result(
        "jobs", "error_log", "Error Log", "look" if look else ("info" if last30 else "ok"),
        f"{n(len(last30), 'error')} in 30 days ({day:,} in the last day), {total:,} kept in all"
        + (f"; the most frequent error repeated {loud:,} times." if loud else "."),
        {"total": total, "last_30d": len(last30), "last_24h": day, "top_repeat": loud}, [{"error (masked)": t, "times": k} for t, k in top],
        "Titles are shortened, with record names, quoted values and numbers masked.",
    )  # fmt: skip


def check_scheduler(c: Ctx):
    sched = c.r.scheduler()
    stopped = c.r.count("Scheduled Job Type", [["stopped", "=", 1]])
    last = c.r.rows("Scheduled Job Type", ["last_execution"], order_by="last_execution desc", limit=1)
    last_run = parse_dt(last[0].get("last_execution")) if last else None
    idle_h = round((c.now - last_run).total_seconds() / 3600, 1) if last_run else None
    failed = c.r.group_count("Scheduled Job Log", "scheduled_job_type", [["status", "=", "Failed"], ["creation", ">=", c.ago(7)]], top=10)
    n_failed = sum(k for _, k in failed)
    flags = []
    if sched.get("status") == "inactive":
        flags.append("the scheduler is off" + (f" ({'; '.join(sched.get('reasons', []))})" if sched.get("reasons") else ""))
    if idle_h is not None and idle_h > 1 and sched.get("status") != "inactive":
        flags.append(f"no scheduled job has run for {idle_h} hours")
    if n_failed:
        flags.append(f"{n_failed:,} scheduled job runs failed in 7 days")
    return result(
        "jobs", "scheduler", "Scheduler and scheduled jobs", "look" if flags else "ok",
        (("Worth a look: " + "; ".join(flags) + ".") if flags else "The scheduler is on and ran within the hour.")
        + f" {n(stopped, 'scheduled job')} stopped.",
        {"status": sched.get("status"), "hours_since_last_run": idle_h, "failed_runs_7d": n_failed, "stopped_jobs": stopped},
        [{"job": str(j).rsplit(".", 1)[-1], "failed runs (7 days)": k} for j, k in failed],
    )  # fmt: skip


def check_queue(c: Ctx):
    j = c.r.jobs()
    flags = []
    if not j.get("workers"):
        flags.append("no background worker is running")
    if j.get("queued", 0) >= 500:
        flags.append(f"{j['queued']:,} jobs waiting")
    if j.get("failed", 0):
        flags.append(f"{j['failed']:,} failed jobs kept")
    items = [q for q in j.get("queues", [])]
    return result(
        "jobs", "queue", "Background jobs", "look" if flags else "ok",
        f"{n(int(j.get('workers') or 0), 'worker')}; {j.get('queued', 0):,} queued, {j.get('started', 0):,} running, "
        f"{j.get('failed', 0):,} failed ({j.get('scope')})." + (" Worth a look: " + "; ".join(flags) + "." if flags else ""),
        {k: j.get(k) for k in ("workers", "queued", "started", "failed", "scope")}, items,
        "Emails, reposts and prepared reports all wait in this queue: a stalled worker stops them all.",
    )  # fmt: skip


def check_log_tables(c: Ctx):
    have = c.exists(*(LOG_DOCTYPES + LEDGER_DOCTYPES))
    counts = {}
    for d in LOG_DOCTYPES:
        if d in have:
            try:
                counts[d] = c.r.count(d)
            except Unavailable:
                continue
    ledger = sum(c.r.count(d) for d in LEDGER_DOCTYPES if d in have)
    try:
        cleared = {r["ref_doctype"]: r.get("days") for r in c.r.rows("Logs To Clear", ["ref_doctype", "days"], parent="Log Settings")}
    except Unavailable:
        cleared = None
    big = [d for d, k in counts.items() if k >= 1_000_000 or (d == "Version" and k > 2 * ledger + 10_000)]
    items = [
        {"log": d, "rows": k, "auto-clear": (f"after {cleared[d]} days" if cleared and d in cleared else ("no" if cleared is not None else "?"))}
        for d, k in sorted(counts.items(), key=lambda x: -x[1])
    ]  # fmt: skip
    return result(
        "jobs", "log_tables", "Log and history tables", "look" if big else "info",
        f"{n(sum(counts.values()), 'row')} across {n(len(counts), 'log table')}, against {n(ledger, 'ledger row')}."
        + (f" Growing large: {', '.join(big)}." if big else ""),
        {"rows": counts, "ledger_rows": ledger, "large": big}, items,
        "Log Settings can clear old rows automatically; the Version table keeps every edit and grows fastest.",
    )  # fmt: skip


def check_email_queue(c: Ctx):
    by = dict(c.r.group_count("Email Queue", "status"))
    stale = c.r.count("Email Queue", [["status", "=", "Not Sent"], ["creation", "<", c.ago(1)]])
    errors = int(by.get("Error", 0))
    return result(
        "jobs", "email_queue", "Email queue", "look" if (stale or errors) else "ok",
        f"{n(errors, 'email')} in error, {stale:,} waiting for over a day."
        + (" By status: " + ", ".join(f"{k} {v:,}" for k, v in sorted(by.items(), key=lambda x: str(x[0]))) + "." if by else ""),
        {"by_status": {str(k): v for k, v in by.items()}, "error": errors, "waiting_over_1_day": stale},
    )  # fmt: skip


CHECKS = (
    check_prepared_reports, check_reports, check_ledgers, check_database,
    check_custom_fields, check_property_setters, check_scripts, check_print_formats, check_core_files,
    check_fill_rates, check_duplicates, check_unused_masters,
    check_reposts, check_old_drafts, check_ledger_health,
    check_roles, check_user_permissions, check_custom_perms,
    check_errors, check_scheduler, check_queue, check_log_tables, check_email_queue,
)  # fmt: skip

_CHECK_IDS = {
    "check_prepared_reports": ("speed", "prepared_reports", "Prepared (background) reports"),
    "check_reports": ("speed", "custom_reports", "Custom reports"),
    "check_ledgers": ("speed", "ledger_size", "Ledger size"),
    "check_database": ("speed", "database", "Database size and settings"),
    "check_custom_fields": ("code", "custom_fields", "Custom fields"),
    "check_property_setters": ("code", "property_setters", "Form changes (Customize Form)"),
    "check_scripts": ("code", "scripts", "Server and client scripts"),
    "check_print_formats": ("code", "print_formats", "Custom print formats"),
    "check_core_files": ("code", "core_files", "Hand-edited core files"),
    "check_fill_rates": ("data", "fill_rates", "Custom fields nobody fills"),
    "check_duplicates": ("data", "duplicates", "Duplicate customers, suppliers and items"),
    "check_unused_masters": ("data", "unused_masters", "Masters nobody uses"),
    "check_reposts": ("stock", "reposts", "Repost Item Valuation queue"),
    "check_old_drafts": ("stock", "old_drafts", "Old draft entries"),
    "check_ledger_health": ("stock", "ledger_health", "Ledger health signals"),
    "check_roles": ("perms", "roles", "Roles and who holds them"),
    "check_user_permissions": ("perms", "user_permissions", "User permissions"),
    "check_custom_perms": ("perms", "custom_perms", "Changed role permissions"),
    "check_errors": ("jobs", "error_log", "Error Log"),
    "check_scheduler": ("jobs", "scheduler", "Scheduler and scheduled jobs"),
    "check_queue": ("jobs", "queue", "Background jobs"),
    "check_log_tables": ("jobs", "log_tables", "Log and history tables"),
    "check_email_queue": ("jobs", "email_queue", "Email queue"),
}

_REASONS = {
    "permission": "this user cannot read it",
    "missing": "not on this site or version",
    "invalid": "this version answered differently",
    "server-error": "the site returned an error",
    "unsupported": "",
    "timeout": "the query took too long",
}


def run_checks(reader: Reader, *, now: Optional[dt.datetime] = None, max_fields: int = 400, progress=None) -> Dict[str, Any]:
    """Run every check. Returns the report data (the JSON file's content)."""
    started = time.time()
    ctx = Ctx(reader, now=now, max_fields=max_fields)
    results = []
    for fn in CHECKS:
        area, cid, title = _CHECK_IDS[fn.__name__]
        if progress:
            progress(f"{dict(AREAS)[area]}: {title}")
        try:
            results.append(fn(ctx))
        except Unavailable as e:
            why = e.detail if e.reason == "unsupported" else (_REASONS.get(e.reason, e.reason) + (f" ({e.detail})" if e.detail else ""))
            results.append(result(area, cid, title, "unavailable", f"Not checked: {why}."))
        except (ReadOnlyViolation, CheckError):
            raise
        except Exception as e:  # a bug in a check must not stop the others
            results.append(result(area, cid, title, "error", f"This check failed ({e.__class__.__name__}: {str(e)[:120]})."))
    areas = []
    for aid, name in AREAS:
        mine = [r for r in results if r["area"] == aid]
        areas.append({"id": aid, "name": name, "look": sum(1 for r in mine if r["status"] == "look"), "checks": mine})
    return {
        "schema": SCHEMA,
        "tool": {"name": "erpnext-check", "version": __version__},
        "generated_at": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "site_time": ctx.now.strftime("%Y-%m-%d %H:%M"),
        "mode": reader.mode,
        "versions": ctx.versions,
        "seconds": round(time.time() - started, 1),
        "areas": areas,
        "read_only": reader.proof(),
    }



# ----------------------------------------------------------------------------------------------------------------
# The report: one self-contained HTML page (no scripts, no external loads) and the same data as JSON
# ----------------------------------------------------------------------------------------------------------------

STATUS_LABEL = {
    "look": "Worth a look",
    "ok": "Nothing stands out",
    "info": "For the record",
    "unavailable": "Not checked",
    "error": "Check failed",
}
AUDIT_URL = "https://mith.tech/services/erpnext-declutter"

_CSS = """
:root{--bg:#fff;--fg:#1a1a1a;--muted:#5c5c5c;--line:#e4e4e4;--well:#f6f6f6;--look:#ff5e29;--lookfg:#fff}
@media (prefers-color-scheme:dark){:root{--bg:#121212;--fg:#ececec;--muted:#a3a3a3;--line:#2c2c2c;--well:#1c1c1c}}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.55 system-ui,-apple-system,
"Segoe UI",Roboto,sans-serif}main{max-width:980px;margin:0 auto;padding:32px 16px 64px}h1{font-size:26px;margin:0 0 4px}
h2{font-size:20px;margin:40px 0 8px;padding-top:16px;border-top:1px solid var(--line)}h3{font-size:16px;margin:0}
.muted{color:var(--muted)}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;margin:20px 0}
.tile{background:var(--well);border-radius:10px;padding:12px}.tile b{display:block;font-size:22px}.tile a{color:inherit;
text-decoration:none}.proof{background:var(--well);border-radius:10px;padding:12px 14px;margin:16px 0}
.check{background:var(--well);border-radius:10px;padding:14px;margin:10px 0}.head{display:flex;gap:10px;align-items:baseline;
justify-content:space-between;flex-wrap:wrap}.pill{font-size:12px;padding:2px 9px;border-radius:99px;background:var(--line);
white-space:nowrap}.pill.look{background:var(--look);color:var(--lookfg)}.check p{margin:6px 0}.note{font-size:13px}
.scroll{overflow-x:auto}table{border-collapse:collapse;margin-top:8px;font-size:13px;width:100%}th,td{text-align:left;
padding:4px 8px;border-bottom:1px solid var(--line);vertical-align:top}th{font-weight:600}td.num{text-align:right;
font-variant-numeric:tabular-nums}dl{display:grid;grid-template-columns:max-content 1fr;gap:2px 12px;margin:8px 0}dt{color:var(--muted)}
dd{margin:0}footer{margin-top:48px;font-size:13px}@media print{.check,.tile,.proof{break-inside:avoid}}
"""


def _e(x: Any) -> str:
    if isinstance(x, float):
        x = f"{x:,.1f}"
    elif isinstance(x, int) and not isinstance(x, bool):
        x = f"{x:,}"
    elif isinstance(x, (list, tuple)):
        x = ", ".join(str(i) for i in x)
    elif x is None:
        x = "–"
    return html.escape(str(x), quote=True)


def _html_table(items: List[Dict[str, Any]], limit: int = 20) -> str:
    rows = [i for i in items if isinstance(i, dict)][:limit]
    if not rows:
        return ""
    cols: List[str] = []
    for r in rows:
        for k in r:
            if k not in cols:
                cols.append(k)
    head = "".join(f"<th>{_e(c)}</th>" for c in cols)
    body = "".join(
        "<tr>"
        + "".join(
            f'<td class="num">{_e(r.get(c))}</td>' if isinstance(r.get(c), (int, float)) and not isinstance(r.get(c), bool)
            else f"<td>{_e(r.get(c))}</td>"
            for c in cols
        )
        + "</tr>"
        for r in rows
    )  # fmt: skip
    more = f'<p class="muted note">{len(items) - limit:,} more rows in the JSON file.</p>' if len(items) > limit else ""
    return f'<div class="scroll"><table><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table></div>{more}'


def render_html(data: Dict[str, Any]) -> str:
    site = data.get("site", {}).get("name", "")
    looks = sum(a["look"] for a in data["areas"])
    tiles = "".join(
        f'<div class="tile"><a href="#{_e(a["id"])}"><span class="muted">{_e(a["name"])}</span>'
        f'<b>{a["look"]}</b><span class="muted">worth a look</span></a></div>'
        for a in data["areas"]
    )
    versions = ", ".join(f"{k} {v}" for k, v in data.get("versions", {}).items() if v) or "unknown"
    sections = []
    for a in data["areas"]:
        checks = []
        for c in a["checks"]:
            checks.append(
                f'<div class="check" id="{_e(c["id"])}"><div class="head"><h3>{_e(c["title"])}</h3>'
                f'<span class="pill {_e(c["status"])}">{_e(STATUS_LABEL.get(c["status"], c["status"]))}</span></div>'
                f"<p>{_e(c['summary'])}</p>{_html_table(c.get('items') or [])}"
                + (f'<p class="muted note">{_e(c["note"])}</p>' if c.get("note") else "")
                + "</div>"
            )
        sections.append(f'<h2 id="{_e(a["id"])}">{_e(a["name"])}</h2>' + "".join(checks))
    ro = data.get("read_only", {})
    return f"""<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>ERPNext check · {_e(site)}</title><style>{_CSS}</style></head>
<body><main>
<h1>ERPNext check</h1>
<p class="muted">{_e(site)} · {_e(data.get("site_time"))} (site time) · {_e(data["mode"])} mode · {_e(versions)}</p>
<p>{looks} {"thing" if looks == 1 else "things"} worth a look across the six areas of an ERPNext declutter audit.
These are signals from counts and settings, not verdicts: each says what to look at, and the audit looks.</p>
<div class="grid">{tiles}</div>
<div class="proof"><b>Read only.</b> {_e(ro.get("statement", ""))}</div>
{"".join(sections)}
<footer class="muted"><p>Made by erpnext-check {_e(data["tool"]["version"])} on your computer in {_e(data.get("seconds"))} s.
This page and the JSON file beside it hold counts and the names of doctypes, fields, reports, roles and scripts;
no customer, supplier, item, user or document is named, and Error Log titles are masked. Nothing was sent anywhere:
share them only if you choose.</p>
<p>The ERPNext declutter audit: {_e(AUDIT_URL)}</p></footer>
</main></body></html>
"""


def write_report(data: Dict[str, Any], out_dir: str, site_label: str) -> Tuple[str, str]:
    slug = re.sub(r"[^a-z0-9.]+|\.{2,}", "-", site_label.lower())
    slug = re.sub(r"-{2,}", "-", slug).strip("-.") or "site"
    stamp = dt.datetime.now().strftime("%Y-%m-%d-%H%M")
    base = os.path.join(out_dir, f"erpnext-check-{slug}-{stamp}")
    os.makedirs(out_dir, exist_ok=True)
    paths = (base + ".html", base + ".json")
    with open(paths[1], "w", encoding="utf-8") as f:
        json.dump(data, f, indent=1, ensure_ascii=False, default=str)
        f.write("\n")
    with open(paths[0], "w", encoding="utf-8") as f:
        f.write(render_html(data))
    return paths


# ----------------------------------------------------------------------------------------------------------------
# Command line
# ----------------------------------------------------------------------------------------------------------------


def _credentials() -> Tuple[str, str]:
    key = os.environ.get("ERPNEXT_API_KEY", "").strip()
    secret = os.environ.get("ERPNEXT_API_SECRET", "").strip()
    if (not key or not secret) and not sys.stdin.isatty():
        raise CheckError("Set ERPNEXT_API_KEY and ERPNEXT_API_SECRET (no terminal to ask in).")
    if not key:
        key = input("API key: ").strip()
    if not secret:
        secret = getpass.getpass("API secret (hidden): ").strip()
    return key, secret


def parse_args(argv: Optional[Sequence[str]] = None) -> argparse.Namespace:
    p = argparse.ArgumentParser(
        prog="erpnext_check.py",
        description="A strictly read-only health check of your own ERPNext site. Writes an HTML report and a JSON "
        "file on this computer; sends nothing anywhere.",
        epilog="API mode: python3 erpnext_check.py https://erp.example.com  (key and secret from ERPNEXT_API_KEY and "
        "ERPNEXT_API_SECRET, or asked for).  Bench mode: cd ~/frappe-bench && env/bin/python erpnext_check.py "
        "--bench --site erp.example.com",
    )
    p.add_argument("site_url", nargs="?", help="API mode: your site's address, e.g. https://erp.example.com")
    p.add_argument("--bench", action="store_true", help="bench mode: run on the server, inside the bench folder")
    p.add_argument("--site", help="bench mode: the site's folder name under sites/")
    p.add_argument("--bench-path", help="bench mode: the bench folder, if not the current one")
    p.add_argument("--out", default=".", help="where to write the report (default: this folder)")
    p.add_argument("--allow-http", action="store_true", help="API mode: allow http:// on a private network")
    p.add_argument("--timeout", type=float, default=60.0, help="API mode: seconds to wait for each answer (60)")
    p.add_argument("--pause", type=float, default=0.0, help="API mode: seconds between requests, for busy sites (0)")
    p.add_argument("--max-fields", type=int, default=400, help="custom fields to measure fill rates for (400)")
    p.add_argument("--version", action="version", version=f"erpnext-check {__version__}")
    a = p.parse_args(argv)
    if a.bench and not a.site:
        p.error("bench mode needs --site")
    if not a.bench and not a.site_url:
        p.error("give your site's address (API mode), or --bench --site <site> on the server")
    return a


def main(argv: Optional[Sequence[str]] = None) -> int:
    a = parse_args(argv)
    say = lambda m: print(m, file=sys.stderr, flush=True)  # noqa: E731
    reader: Optional[Reader] = None
    try:
        if a.bench:
            reader = BenchReader(a.site, a.bench_path)
            label = a.site
        else:
            key, secret = _credentials()
            reader = ApiReader(a.site_url, key, secret, timeout=a.timeout, pause=a.pause, allow_http=a.allow_http)
            label = urllib.parse.urlsplit(reader.base).netloc
            del key, secret
        say(f"Reading {label} ({reader.mode} mode, read-only)…")
        data = run_checks(reader, max_fields=a.max_fields, progress=lambda m: say(f"  {m}"))
        data["site"] = {"name": label}
        reader.close()
        reader = None
        html_path, json_path = write_report(data, a.out, label)
    except ReadOnlyViolation as e:
        say(f"\nStopped: {e}\nThis is a bug in the tool, and nothing was written to your site. Please tell us.")
        return 3
    except CheckError as e:
        say(f"\n{e}")
        return 1
    except KeyboardInterrupt:
        say("\nStopped.")
        return 130
    finally:
        if reader is not None:
            reader.close()
    say("")
    for area in data["areas"]:
        say(f"  {area['name']:<28} {area['look']} worth a look")
    say(f"\n{data['read_only']['statement']}\n\nReport: {html_path}\nData:   {json_path}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
