#!/usr/bin/env python3
"""Ground an assistant on LiquiLens records and check its figures, with Python 3.11+ and no model.

One run resolves a bank or NBFC name with ontology_context on the LiquiLens MCP server, follows the
server's own coverage entries for three record tools only, checks the seal on each record, and, given a
draft, marks every number in it as found or not found in the records it just read.

The key, if any, is read from the LIQUILENS_API_KEY environment variable and sent only as an
Authorization header to https://api.liquilens.in/mcp. It is never put in a URL, never taken from the
command line and never printed. Without a key the free view answers, with its lower limits.

The figure check is numeric membership against cited public records: a number is found when the
records contain the same value, and a percentage matches only a percentage. It is not a judgement that
a sentence is true. The rules mirror LiquiLens backend/ai_claims.py (number_tokens and numeric_support)
at commit 086dce60, and the seal check mirrors backend/review_packet.py canonical_sha256.

No model call, automatic retry, scheduler or filesystem write. Exit codes: 0 every number found (or no
draft given), 2 the name did not resolve to one institution, 3 at least one number was not found,
1 a transport, protocol or input error.
"""
import argparse
from datetime import datetime, timezone
from decimal import Decimal, InvalidOperation
import hashlib
import json
import math
import os
from queue import Empty, Queue
import re
import sys
from threading import Thread
from urllib.error import HTTPError, URLError
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener

VERSION = "1.1.0"  # the client identity in developers/recipes/manifest.json
PYTHON = (3, 11)
CLIENT_INFO = {"name": "liquilens-research-recipes", "version": VERSION}
PROTOCOL = "2025-11-25"
SUPPORTED_PROTOCOLS = (PROTOCOL, "2025-06-18", "2025-03-26")
ENDPOINT = "https://api.liquilens.in/mcp"
KEY_ENV = "LIQUILENS_API_KEY"
TIMEOUT = 20
MAX_BYTES = 2 * 1024 * 1024
MAX_DRAFT_CHARS = 20000
MAX_READS = 3
RESOLVER = "ontology_context"
EXIT_OK, EXIT_ERROR, EXIT_UNRESOLVED, EXIT_NOT_FOUND = 0, 1, 2, 3
# The only record tools this recipe follows, with the arguments it accepts from a coverage entry.
ALLOWED_READS = ("institution_review_packet", "bank_asset_quality_review", "institution_evidence_monitor")
ARGUMENTS = {
    "institution_review_packet": {"institution": "text"},
    "bank_asset_quality_review": {"slug": "slug", "as_of": "date", "include_history": "flag"},
    "institution_evidence_monitor": {"slug": "slug", "as_of": "date", "include_history": "flag"},
}
# District and housing reads are never followed by this recipe, whatever the server offers.
EXCLUDED_READS = ("lending_geography", "bank_credit_land_stress")
SLUG = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
DAY = re.compile(r"\d{4}-\d{2}-\d{2}")
CANONICAL_ID = re.compile(r"[a-z]+:[a-z0-9-]+/[a-z0-9-]+/[a-z0-9-]+")
CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f]")
SEAL = "content_sha256"
BOUNDARY = ("Numeric membership against cited public records, not a judgement that a sentence is true, and not "
            "verification of past risk or return claims. Records are research screens over public filings, not "
            "ratings or investment advice.")

# MIRROR of LiquiLens backend/ai_claims.py at 086dce60: numbers, dates and fraction fields.
NUM_RE = re.compile(
    r"(?<![\w.])([+\-\u2212]?(?:(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|\.\d+)(?:[eE][+\-]?\d+)?)\s*"
    r"(%|percent\b|per cent\b)?",
    re.I,
)
DATE_RE = re.compile(r"\b\d{4}-\d{2}-\d{2}(?:T[0-9:.]+(?:Z|[+\-]\d{2}:\d{2})?)?")
FRACTION_FIELDS = frozenset({"pd_12m", "pd_24m", "pd_36m", "pd", "probability", "default_probability"})
SKIPPED_KEYS = frozenset({"question", "query", "source", "endpoint", "source_url", "url", "slug", "id",
                          "evidence_id"})
PERCENT_UNITS = frozenset({"%", "percent", "percentage", "per cent", "per cent per year"})


class ResearchError(Exception):
    """A transport, protocol or input error; never a research conclusion."""


def parse_json(raw):
    def invalid_constant(value):
        raise ValueError("non-finite JSON value: " + value)

    try:
        return json.loads(raw, parse_constant=invalid_constant)
    except (ValueError, UnicodeError) as exc:
        raise ResearchError("response is not valid finite JSON") from exc


class NoRedirects(HTTPRedirectHandler):
    def redirect_request(self, *_args, **_kwargs):
        raise ResearchError("redirect refused; only the documented endpoint is allowed")


def read_response(response, payload):
    """Stop an SSE response at our reply, even if the server keeps the stream open."""
    content_type = response.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
    if content_type != "text/event-stream":
        raw = response.read(MAX_BYTES + 1)
        if len(raw) > MAX_BYTES:
            raise ResearchError("response exceeds the 2 MiB limit")
        return raw
    consumed, lines = 0, []
    while True:
        line = response.readline(MAX_BYTES - consumed + 1)
        consumed += len(line)
        if consumed > MAX_BYTES:
            raise ResearchError("response exceeds the 2 MiB limit")
        if not line:
            raise ResearchError("event stream ended before the matching JSON-RPC response")
        line = line.rstrip(b"\r\n")
        if not line and lines:
            raw = b"\n".join(lines)
            value = parse_json(raw)
            if isinstance(value, dict) and type(value.get("id")) is int and value["id"] == payload.get("id"):
                return raw
            lines = []
        elif line.startswith(b"data:"):
            data = line[5:]
            lines.append(data[1:] if data.startswith(b" ") else data)


def _exchange(url, payload, headers):
    """One bounded POST; called inside a deadline-limited daemon thread."""
    if url != ENDPOINT:
        raise ResearchError("endpoint is not allowed")
    request = Request(url, data=json.dumps(payload).encode(), headers=headers, method="POST")
    try:
        with build_opener(ProxyHandler({}), NoRedirects()).open(request, timeout=TIMEOUT) as response:
            raw = read_response(response, payload)
            if response.status not in (200, 202, 204):
                raise ResearchError("unexpected HTTP status " + str(response.status))
            return response.status, dict(response.headers.items()), raw
    except HTTPError as exc:
        raise ResearchError("HTTP " + str(exc.code) + "; no automatic retry") from exc
    except (URLError, OSError) as exc:
        raise ResearchError("network request failed or timed out") from exc


def exchange(url, payload, headers):
    # Socket timeouts alone can be extended by a slowly trickling response, so a daemon worker
    # enforces the wall-clock deadline. The CLI exits on failure and never retries the read.
    result = Queue(maxsize=1)

    def run():
        try:
            result.put((True, _exchange(url, payload, headers)))
        except Exception as exc:
            result.put((False, exc))

    Thread(target=run, daemon=True).start()
    try:
        succeeded, value = result.get(timeout=TIMEOUT)
    except Empty as exc:
        raise ResearchError("20-second request deadline exceeded; no automatic retry") from exc
    if not succeeded:
        raise value
    return value


def key_from_environment(environ=None):
    """The key from LIQUILENS_API_KEY, or None. A malformed value is refused, never sent."""
    value = (os.environ if environ is None else environ).get(KEY_ENV, "")
    if not value:
        return None
    if len(value) > 512 or not re.fullmatch(r"[\x21-\x7e]+", value):
        raise ResearchError(KEY_ENV + " is set but is not a printable key without spaces")
    return value


class Client:
    def __init__(self, *, key=None, verification=False, transport=exchange):
        self.transport = transport
        self.sequence = 0
        self.session = None
        self.protocol = PROTOCOL
        self.headers = {
            "Content-Type": "application/json",
            "Accept": "application/json, text/event-stream",
            "User-Agent": "LiquiLens-Operator-Growth-Audit/1.0" if verification
            else "liquilens-research-recipes/" + VERSION,
        }
        if key:
            self.headers["Authorization"] = "Bearer " + key
        if verification:
            self.headers["X-Liquilens-Traffic-Class"] = "synthetic"

    def request(self, method, params=None, *, notification=False):
        self.sequence += 1
        payload = {"jsonrpc": "2.0", "method": method, "params": params or {}}
        if not notification:
            payload["id"] = self.sequence
        headers = dict(self.headers)
        if self.session:
            headers["Mcp-Session-Id"] = self.session
        status, received_headers, raw = self.transport(ENDPOINT, payload, headers)
        received_headers = {key.lower(): value for key, value in received_headers.items()}
        if notification:
            if status not in (200, 202, 204) or raw.strip():
                raise ResearchError("initialization notification was not accepted")
            return None
        if status != 200:
            raise ResearchError("MCP request did not return HTTP 200")
        message = parse_json(raw)
        if (not isinstance(message, dict) or message.get("jsonrpc") != "2.0"
                or type(message.get("id")) is not int or message["id"] != self.sequence):
            raise ResearchError("invalid or mismatched JSON-RPC response")
        if "error" in message:
            raise ResearchError("MCP rejected " + method + ": " + clean(message["error"])[:500])
        result = message.get("result")
        if not isinstance(result, dict):
            raise ResearchError("MCP response has no result object")
        if method == "initialize":
            if result.get("protocolVersion") not in SUPPORTED_PROTOCOLS:
                raise ResearchError("server did not negotiate a supported MCP version")
            self.protocol = result["protocolVersion"]
            self.session = received_headers.get("mcp-session-id")
        return result

    def initialize(self):
        self.request("initialize", {"protocolVersion": PROTOCOL, "capabilities": {}, "clientInfo": CLIENT_INFO})
        self.headers["MCP-Protocol-Version"] = self.protocol
        self.request("notifications/initialized", notification=True)

    def call(self, name, arguments):
        """A tool's JSON record. A refusal (isError) is returned as a reason, never as a record."""
        result = self.request("tools/call", {"name": name, "arguments": arguments})
        if result.get("isError", False) is not False:
            texts = [row.get("text") for row in result.get("content", [])
                     if isinstance(row, dict) and row.get("type") == "text" and isinstance(row.get("text"), str)]
            return None, clean(" ".join(texts))[:500] or "the tool refused the request"
        record = result.get("structuredContent")
        if record is None:
            texts = [row.get("text") for row in result.get("content", [])
                     if isinstance(row, dict) and row.get("type") == "text"]
            if not texts or not isinstance(texts[0], str):
                raise ResearchError("MCP tool " + name + " returned no JSON record")
            record = parse_json(texts[0])
        if not isinstance(record, dict):
            raise ResearchError("MCP tool " + name + " record must be an object")
        return record, None


# ---------------------------------------------------------------------------------------------------------
# Seals and figures
# ---------------------------------------------------------------------------------------------------------
def canonical_sha256(value):
    """MIRROR of LiquiLens backend/review_packet.py canonical_sha256: sorted keys, compact UTF-8 JSON."""
    body = json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
    return hashlib.sha256(body.encode("utf-8")).hexdigest()


def seal_state(record):
    """How the record's top-level seal stands: holds, broken, unsealed (a withheld-depth view) or none."""
    claimed = record.get(SEAL)
    if isinstance(claimed, str):
        body = {key: value for key, value in record.items() if key != SEAL}
        try:
            return "holds" if canonical_sha256(body) == claimed else "broken"
        except (TypeError, ValueError):
            return "broken"
    if record.get("sealed") is False:
        return "unsealed"
    return "none"


def decimal_value(value):
    """MIRROR of ai_claims.decimal_value: a finite decimal, or None."""
    if isinstance(value, bool) or value is None:
        return None
    text = str(value).strip().replace("\u2212", "-").replace(",", "")
    if len(text) > 128:
        return None
    try:
        number = Decimal(text)
    except InvalidOperation:
        return None
    if not number.is_finite() or not -308 <= number.adjusted() <= 308 or not math.isfinite(float(number)):
        return None
    return number


def number_tokens(text):
    """MIRROR of ai_claims.number_tokens: (value, is_percent) for each number; dates are not amounts."""
    text = DATE_RE.sub(" ", text)
    out = []
    for match in NUM_RE.finditer(text):
        number = decimal_value(match[1])
        if number is not None:
            out.append((match[1], number, bool(match[2])))
    return out


def numeric_support(records):
    """MIRROR of ai_claims.numeric_support over every record read: plain values and percentages."""
    plain, percentages, visited = set(), set(), 0

    def walk(value, key="", unit="", depth=0):
        nonlocal visited
        visited += 1
        if visited > 20000 or depth > 16:
            return
        if isinstance(value, dict):
            local_unit = str(value.get("unit", value.get("units", unit))).lower()
            for child_key, child in list(value.items())[:512]:
                if child_key not in SKIPPED_KEYS:
                    walk(child, str(child_key), local_unit, depth + 1)
        elif isinstance(value, list):
            for child in value[:512]:
                walk(child, key, unit, depth + 1)
        elif isinstance(value, (int, float, str)) and not isinstance(value, bool):
            number = decimal_value(value)
            if number is None:
                return
            plain.add(number)
            if key in FRACTION_FIELDS or key.endswith(("_fraction", "_probability")):
                percentages.add(number * 100)
            elif unit in PERCENT_UNITS:
                percentages.add(number)

    walk(records)
    return plain, percentages


def check_figures(draft, records):
    plain, percentages = numeric_support(records)
    return [{"text": text, "value": str(number), "percent": percent,
             "found": number in (percentages if percent else plain)}
            for text, number, percent in number_tokens(draft)]


def clean(value):
    """Server text is data: control characters never reach the terminal."""
    text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False, sort_keys=True)
    return CONTROL.sub(" ", text)


# ---------------------------------------------------------------------------------------------------------
# The run
# ---------------------------------------------------------------------------------------------------------
def checked_arguments(tool, arguments):
    """The coverage entry's arguments, passed exactly, when every one is a bounded value this tool takes."""
    rules = ARGUMENTS[tool]
    if not isinstance(arguments, dict) or not arguments or set(arguments) - set(rules):
        return None
    for name, value in arguments.items():
        kind = rules[name]
        if kind == "text" and not (isinstance(value, str) and 1 <= len(value) <= 200):
            return None
        if kind == "slug" and not (isinstance(value, str) and len(value) <= 120 and SLUG.fullmatch(value)):
            return None
        if kind == "date" and not (isinstance(value, str) and DAY.fullmatch(value)):
            return None
        if kind == "flag" and type(value) is not bool:
            return None
    return dict(arguments)


def as_of_fields(record):
    """The record's own clocks, as served."""
    return {key: record[key] for key in ("as_of", "served_as_of", "period_end", "available_at", "retrieved_at")
            if isinstance(record.get(key), str)}


def ground(query, *, draft=None, key=None, verification=False, max_reads=MAX_READS, transport=exchange):
    query = query.strip() if isinstance(query, str) else ""
    if not 1 <= len(query) <= 200:
        raise ResearchError("give a name, key or canonical id of 1 to 200 characters")
    if draft is not None and len(draft) > MAX_DRAFT_CHARS:
        raise ResearchError("the draft is longer than 20,000 characters")
    if type(max_reads) is not int or not 1 <= max_reads <= MAX_READS:
        raise ResearchError("--max-reads must be 1, 2 or 3")
    client = Client(key=key, verification=verification, transport=transport)
    client.initialize()
    out = {"schema": "liquilens.assistant-grounding-recipe.v1", "query": query, "endpoint": ENDPOINT,
           "key_used": bool(key), "verification": verification, "outcome": "records_read",
           "boundary": BOUNDARY, "execution_authority": False, "reads": [], "not_followed": []}
    context, refusal = client.call(RESOLVER, {"q": query, "view": "summary"})
    if context is None:
        raise ResearchError("ontology_context refused the request: " + refusal)
    status = context.get("status")
    if status in ("ambiguous", "not_found"):
        candidates = context.get("candidates", [])
        out.update(outcome=status, candidates=[clean(c) for c in candidates if isinstance(c, str)][:20])
        return _finish(out)
    object_id = context.get("id")
    if status != "resolved" or not isinstance(object_id, str) or not CANONICAL_ID.fullmatch(object_id):
        raise ResearchError("the context answer does not name one canonical id")
    out["entity"] = {"id": object_id, "label": clean(context.get("label") or ""), "kind": context.get("kind")}
    if context.get("kind") != "inst":
        out["outcome"] = "not_an_institution"
        return _finish(out)
    records = []
    for entry in context.get("coverage") or []:
        call = entry.get("mcp") if isinstance(entry, dict) else None
        tool = call.get("tool") if isinstance(call, dict) else None
        if not isinstance(call, dict) or call.get("server") != ENDPOINT:
            out["not_followed"].append({"tool": clean(tool or ""), "reason": "not a read on " + ENDPOINT})
            continue
        if tool not in ALLOWED_READS or tool in EXCLUDED_READS:
            out["not_followed"].append({"tool": clean(tool or ""), "reason": "outside this recipe's record reads"})
            continue
        arguments = checked_arguments(tool, call.get("arguments"))
        if arguments is None:
            out["not_followed"].append({"tool": tool, "reason": "arguments this recipe does not pass"})
            continue
        if len(out["reads"]) >= max_reads:
            out["not_followed"].append({"tool": tool, "reason": "over the read limit for one run"})
            continue
        record, refusal = client.call(tool, arguments)
        read = {"tool": tool, "arguments": arguments}
        if record is None:
            read.update(status="refused", reason=refusal)
        else:
            read.update(status=clean(record.get("status") or "returned"), clocks=as_of_fields(record),
                        seal=seal_state(record))
            records.append({"tool": tool, "record": record})
        out["reads"].append(read)
    if draft is not None:
        out["figures"] = check_figures(draft, [row["record"] for row in records])
        out["outcome"] = "checked"
    out["records"] = records
    return _finish(out)


def _finish(out):
    out["retrieved_at"] = datetime.now(timezone.utc).isoformat()
    return out


def render(result):
    lines = []
    if result["outcome"] in ("ambiguous", "not_found"):
        lines.append(f"{clean(result['query'])}: {result['outcome'].replace('_', ' ')}. Nothing is guessed.")
        lines += [f"  candidate {c}" for c in result.get("candidates", [])]
        return "\n".join(lines)
    entity = result["entity"]
    lines.append(f"{entity['label']}  {entity['id']}")
    if result["outcome"] == "not_an_institution":
        lines.append(f"This is a {clean(entity.get('kind'))} object, not an institution; the recipe stops here.")
        return "\n".join(lines)
    for read in result["reads"]:
        if read["status"] == "refused":
            lines.append(f"  {read['tool']}: refused: {read['reason']}")
            continue
        clocks = ", ".join(f"{k} {clean(v)}" for k, v in read["clocks"].items()) or "no clock served"
        lines.append(f"  {read['tool']}: {read['status']}; {clocks}; seal {read['seal']}")
    for skipped in result["not_followed"]:
        lines.append(f"  not followed: {skipped['tool'] or 'an entry'} ({skipped['reason']})")
    if "figures" in result:
        found = sum(row["found"] for row in result["figures"])
        lines.append(f"Figures in the draft: {found} of {len(result['figures'])} found in the records read.")
        lines += [f"  {'found    ' if row['found'] else 'NOT FOUND'} {clean(row['text'])}"
                  f"{' percent' if row['percent'] else ''}" for row in result["figures"]]
    lines.append(BOUNDARY)
    return "\n".join(lines)


def exit_code(result):
    if result["outcome"] in ("ambiguous", "not_found", "not_an_institution"):
        return EXIT_UNRESOLVED
    if any(not row["found"] for row in result.get("figures", [])):
        return EXIT_NOT_FOUND
    return EXIT_OK


def read_draft(path):
    if path == "-":
        return sys.stdin.read(MAX_DRAFT_CHARS + 1)
    with open(path, encoding="utf-8") as handle:
        return handle.read(MAX_DRAFT_CHARS + 1)


def main(argv=None):
    parser = argparse.ArgumentParser(
        description="Resolve a bank or NBFC on LiquiLens, read its cited records and check a draft's figures. "
                    f"A key, if any, comes only from the {KEY_ENV} environment variable.")
    parser.add_argument("name", help="a bank or NBFC name, key or canonical id")
    parser.add_argument("--draft", metavar="PATH", help="a text file with the assistant's draft; - reads stdin")
    parser.add_argument("--json", action="store_true", help="print the complete result as JSON")
    parser.add_argument("--max-reads", type=int, default=MAX_READS, help="record reads in one run, 1 to 3")
    parser.add_argument("--verification", action="store_true", help=argparse.SUPPRESS)
    args = parser.parse_args(argv)
    if sys.version_info < PYTHON:
        print(json.dumps({"outcome": "error", "reason": "Python %d.%d or newer is required" % PYTHON}),
              file=sys.stderr)
        return EXIT_ERROR
    try:
        draft = read_draft(args.draft) if args.draft else None
        result = ground(args.name, draft=draft, key=key_from_environment(), verification=args.verification,
                        max_reads=args.max_reads, transport=exchange)
    except (ResearchError, OSError, UnicodeError) as exc:
        print(json.dumps({"outcome": "error", "reason": str(exc)}), file=sys.stderr)
        return EXIT_ERROR
    print(json.dumps(result, ensure_ascii=False, indent=2) if args.json else render(result))
    return exit_code(result)


if __name__ == "__main__":
    raise SystemExit(main())
