#!/usr/bin/env python3
"""Optional offline inference helper for K-Diagnostics (stdin JSON -> stdout JSON)."""
import json
import re
import sys

CODE_RE = re.compile(r"\b(?:P|C|B|U)[0-9A-F]{4,5}\b", re.I)


def extract_codes(text):
    seen = set()
    out = []
    for m in CODE_RE.finditer(text or ""):
        c = m.group(0).upper()
        if c not in seen:
            seen.add(c)
            out.append(c)
    return out[:24]


def main():
    try:
        raw = sys.stdin.read()
        req = json.loads(raw or "{}")
    except Exception as ex:
        print(json.dumps({"ok": False, "error": str(ex)}))
        return 1

    prompt = (req.get("prompt") or "").strip()
    codes = extract_codes(prompt)
    severity = "low"
    if any(c.startswith("U") for c in codes):
        severity = "high"
    elif len(codes) >= 3:
        severity = "medium"

    summary = "Local helper analysis."
    if not codes:
        summary = "No standard fault codes detected in the supplied context."
    else:
        summary = "Detected fault codes: " + ", ".join(codes) + "."

    checks = [
        "Verify battery voltage and ignition state.",
        "Confirm the selected model matches the connected vehicle.",
        "Re-read faults after a short drive cycle if intermittent.",
    ]

    escalate = len(codes) >= 5 or any(c.startswith("U") for c in codes)

    out = {
        "ok": True,
        "confidence": 0.5 if codes else 0.35,
        "escalate": escalate,
        "severity": severity,
        "fault_summary": summary,
        "likely_causes": ["Further workshop verification recommended."],
        "checks": checks,
        "related_parameters": [],
        "customer_report": summary + " A qualified workshop should confirm repairs before clearing faults.",
        "source": "python_helper",
    }
    print(json.dumps(out))
    return 0


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