"""Public, no-login shareable medical summary page.

Doubles as two things at the same URL: the "show this to the doctor at a
regular appointment" quick summary, and the emergency-room quick-access card.
Same page, same token — a doctor or paramedic won't have, and shouldn't need,
a Memodoc account either way. Security comes from the token being long and
unguessable (like any share link), not from authentication; the caregiver can
regenerate it at any time from /perfiles/<id>/emergencia if it's over-shared.
"""
import base64
from io import BytesIO

from flask import Blueprint, render_template, abort, url_for, request

from app.models import Patient, MedicalEvent

emergency_bp = Blueprint(
    "emergency", __name__, url_prefix="/emergencia", template_folder="../templates/emergency"
)


def _qr_data_uri(data: str) -> str:
    import qrcode

    img = qrcode.make(data, box_size=6, border=2)
    buffer = BytesIO()
    img.save(buffer, format="PNG")
    encoded = base64.b64encode(buffer.getvalue()).decode("ascii")
    return f"data:image/png;base64,{encoded}"


@emergency_bp.route("/<token>")
def view(token):
    patient = Patient.query.filter_by(emergency_token=token).first()
    if patient is None:
        abort(404)

    diagnoses = [e for e in patient.medical_events if e.event_type == "diagnosis"][:10]
    medications = [e for e in patient.medical_events if e.event_type == "medication"][:10]
    allergies = [e for e in patient.medical_events if e.event_type == "allergy"][:10]
    summary = patient.latest_summary()

    qr_uri = _qr_data_uri(url_for("emergency.view", token=token, _external=True))

    return render_template(
        "emergency/view.html",
        patient=patient,
        summary=summary,
        diagnoses=diagnoses,
        medications=medications,
        allergies=allergies,
        qr_uri=qr_uri,
    )
