# ============================================================
# 02 — Hospital: finding the clinical record that justifies a bill
#
# Colab:  !pip install winnex-madhava
#
# THE REAL PROBLEM
#   A health insurer denies a claim. The hospital's revenue cycle team
#   has to produce the clinical documentation that proves the procedure
#   was justified — usually within 30 days, or the revenue is lost.
#
#   The documentation exists. It is in the EHR. The question is
#   whether the search finds it. When the search says "no matching
#   record", the bill is written off — and nobody can tell whether the
#   record truly does not exist or the index simply failed to surface it.
#
#   This is a financial problem with an audit trail requirement: every
#   denial that is not appealed is money the hospital already earned.
#
# WHAT THIS EXAMPLE MODELS
#   A clinical document store (Cerner, Epic, MV, Tasy all keep notes
#   in a relational table). We load clinical notes, search for the
#   justification of a specific procedure, and show the difference
#   between "not found" and "proven not present".
# ============================================================

# instalação automática — Colab, Jupyter e script local.
# No Colab, "!pip" dentro de comentário não executa: a instalação
# precisa acontecer de dentro da célula, antes dos imports.
import importlib
import subprocess
import sys

for _pkg in ["winnex-madhava"]:
    _mod = _pkg.replace("-", "_")
    try:
        __import__(_mod)
        continue
    except ImportError:
        pass
    _r = subprocess.run(
        [sys.executable, "-m", "pip", "install", "-q", "--upgrade", _pkg],
        capture_output=True, text=True
    )
    # O interpretador do Colab já está em execução quando o pip termina.
    # Sem invalidar o cache, o import abaixo pode não enxergar o pacote.
    importlib.invalidate_caches()
    try:
        __import__(_mod)
    except ImportError:
        sys.stderr.write(_r.stdout or "")
        sys.stderr.write(_r.stderr or "")
        raise SystemExit(
            "\n\nNão foi possível importar " + _pkg + " após instalar.\n"
            "No Colab: menu 'Ambiente de execução' -> 'Reiniciar sessão',\n"
            "e execute esta célula novamente.\n"
        )

import sqlite3
import numpy as np
import winnex_madhava as mad

DIM = 256

def embed(text: str) -> np.ndarray:
    """Demo embedding. In production, use a clinical encoder."""
    v = np.zeros(DIM, dtype=np.float32)
    for token in text.lower().split():
        for i, ch in enumerate(token):
            v[(ord(ch) * 31 + i * 7) % DIM] += 1.0
    n = np.linalg.norm(v)
    return v / n if n else v

# ── 1. clinical notes as stored in the EHR ──────────────────
conn = sqlite3.connect(":memory:")
conn.execute("""
    CREATE TABLE notas_clinicas (
        id                INTEGER PRIMARY KEY,
        paciente_id       TEXT,
        data_atendimento  TEXT,
        tipo              TEXT,
        profissional      TEXT,
        texto             TEXT
    )
""")

notas = [
    ("PAC-4471", "2026-03-02", "evolução", "Dr. Almeida",
     "Paciente com dor abdominal intensa em quadrante inferior direito há "
     "18 horas, associada a febre de 38,4°C e leucocitose de 15.200. "
     "Exame físico com defesa localizada e sinal de Blumberg positivo. "
     "Hipótese diagnóstica: apendicite aguda. Indicada videolaparoscopia "
     "de urgência."),

    ("PAC-4471", "2026-03-02", "descrição cirúrgica", "Dr. Almeida",
     "Realizada apendicectomia videolaparoscópica sob anestesia geral. "
     "Achado intraoperatório: apêndice cecal inflamado, sem perfuração. "
     "Procedimento transcorreu sem intercorrências. Tempo cirúrgico: "
     "55 minutos."),

    ("PAC-4471", "2026-03-04", "evolução", "Dra. Ribeiro",
     "Primeiro dia pós-operatório. Paciente estável, afebril, com dieta "
     "líquida aceita. Ferida operatória sem sinais de infecção. "
     "Alta hospitalar prevista para amanhã."),

    ("PAC-4471", "2026-03-05", "sumário de alta", "Dra. Ribeiro",
     "Paciente recebe alta em bom estado geral. Diagnóstico final: "
     "apendicite aguda supurada, tratada por videolaparoscopia. "
     "Prescrição de analgesia domiciliar e retorno ambulatorial em 10 dias."),

    ("PAC-8823", "2026-03-03", "evolução", "Dr. Santos",
     "Paciente com quadro de insuficiência cardíaca descompensada. "
     "Dispneia aos pequenos esforços, edema de membros inferiores. "
     "Iniciado diurético endovenoso, com melhora progressiva."),

    ("PAC-8823", "2026-03-06", "evolução", "Dr. Santos",
     "Melhora clínica significativa. Redução do edema e da dispneia. "
     "Ajustada medicação oral. Programada alta com acompanhamento "
     "cardiológico ambulatorial."),

    ("PAC-3310", "2026-02-18", "evolução", "Dra. Lima",
     "Consulta ambulatorial de rotina. Paciente hipertenso controlado, "
     "sem queixas. Mantida medicação. Retorno em seis meses."),
]

for i, (pac, data, tipo, prof, texto) in enumerate(notas, start=1):
    conn.execute(
        "INSERT INTO notas_clinicas VALUES (?,?,?,?,?,?)",
        (i, pac, data, tipo, prof, texto),
    )
conn.commit()

# ── 2. load the notes for the patient under dispute ─────────
# PHI stays inside the hospital. This index never leaves the premises.
paciente = "PAC-4471"
rows = conn.execute("""
    SELECT id, tipo, data_atendimento, texto
    FROM notas_clinicas
    WHERE paciente_id = ?
    ORDER BY id
""", (paciente,)).fetchall()

textos = [f"{r[1]} — {r[2]}. {r[3]}" for r in rows]
corpus = np.stack([embed(t) for t in textos]).astype(np.float32)

print(f"patient under dispute : {paciente}")
print(f"clinical notes on file: {len(rows)}\n")

# ── 3. index ────────────────────────────────────────────────
engine = mad.build_engine(
    corpus, dim=DIM, metric="cosine", k=3,
    k1_fraction=1.0, postfilter=True, audit_exhaustive=True,
)

# ── 4. the insurer's question ───────────────────────────────
consulta = "justificativa clínica para realização de videolaparoscopia"

r = mad.retrieve(engine, embed(consulta), corpus_text=textos, k=3)

print(f"insurer's question: {consulta}\n")
print("documentation produced:")
q = embed(consulta)
for pos, idx in enumerate(r["indices"], 1):
    score = float(np.dot(q, corpus[idx]))
    print(f"  {pos}. [{score:.3f}] {rows[idx][1]} de {rows[idx][2]}")
    print(f"       {rows[idx][3][:88]}...")

# ── 5. the difference that decides the appeal ──────────────
print(f"\n─── what the hospital can now state ───")
print(f"  notes supporting the procedure : {len(r['indices'])}")
print(f"  notes excluded with proof      : {len(textos) - len(r['indices'])}")
print(f"  bound violations               : {r['bound_violations']}")

assert r["bound_violations"] == 0

total_notas = len(textos)
recuperadas = len(r["indices"])
excluidas = total_notas - recuperadas

print(f"""
This is the sentence that wins the appeal
─────────────────────────────────────────
"Of the {total_notas} notes in this patient's record, {recuperadas} were identified as
supporting the procedure, and the remaining {excluidas} were excluded on the
basis of a mathematical bound proving they are not responsive to
this query."

An approximate search gives the same {recuperadas} notes and cannot say the
second half. When the payer challenges the search — and auditors do —
the hospital has evidence rather than assurance.
""")

# ── 6. the financial framing ────────────────────────────────
print("Why the revenue cycle team cares")
print("─" * 60)
print("""A denied claim that is not appealed is revenue the hospital
already earned and will never collect. The work of appealing is
searching the record for justification — and every search that
returns "nothing found" is a claim written off. What matters is
knowing whether nothing was found or nothing was *proven* absent.
""")

conn.close()
