#!/usr/bin/env python3
"""LockedIn Labs: read synthetic FHIR R4 eligibility facts without inventing approval.

Python 3.11+, standard library only. No network, patient data, or writes.
Original fixtures use invented references and service codes. This narrow mapper
is not a full FHIR/profile validator, payer adapter, or clinical decision tool.
"""
from __future__ import annotations

import argparse
import json
from copy import deepcopy
from dataclasses import asdict, dataclass


@dataclass(frozen=True)
class Question:
    patient: str = "Patient/SYNTHETIC-PERSON"
    coverage: str = "Coverage/SYNTHETIC-PLAN"
    request: str = "CoverageEligibilityRequest/SYNTHETIC-REQUEST"
    insurer: str = "Organization/SYNTHETIC-PAYER"
    service_date: str = "2026-10-22"
    code_system: str = "https://example.invalid/synthetic-services"
    service_code: str = "SYNTHETIC-VISIT"


def response() -> dict:
    """A teaching resource with no real person, clinical code or payer endpoint."""
    q = Question()
    return {
        "resourceType": "CoverageEligibilityResponse",
        "id": "SYNTHETIC-RESPONSE", "status": "active",
        "purpose": ["validation", "auth-requirements"],
        "patient": {"reference": q.patient}, "servicedDate": q.service_date,
        "created": "2026-10-22T13:00:00Z", "request": {"reference": q.request},
        "outcome": "complete", "insurer": {"reference": q.insurer},
        "insurance": [{
            "coverage": {"reference": q.coverage}, "inforce": True,
            "item": [{
                "productOrService": {"coding": [{"system": q.code_system, "code": q.service_code}]},
                "authorizationRequired": True,
            }],
        }],
    }


def reference(value: dict, key: str) -> str | None:
    field = value.get(key)
    return field.get("reference") if isinstance(field, dict) else None


def has_modifier_extension(value: object) -> bool:
    if isinstance(value, dict):
        return bool(value.get("modifierExtension")) or any(has_modifier_extension(v) for v in value.values())
    if isinstance(value, list):
        return any(has_modifier_extension(v) for v in value)
    return False


def interpret(question: Question, body: dict, http_status: int = 200,
              *, default_missing_to_false: bool = False) -> dict:
    """Read a bounded fact from a trusted fixture; preserve every unanswered question.

    The policy intentionally requires a complete response for one exact service
    date and code. R4 supports other forms; extending this mapper needs an explicit
    adapter contract. First failed check wins. Neither argument is mutated.
    """
    trace: list[str] = []
    evidence: list[dict] = []

    def observed(path: str, value: object, meaning: str) -> None:
        evidence.append({"path": path, "value": value, "meaning": meaning})

    def result(state: str, reason: str, action: str, required: bool | None = None) -> dict:
        return {
            "state": state, "reason": reason, "authorization_required": required,
            "not_established": ["authorization_approval", "claim_payment", "patient_responsibility"],
            "owner": "benefits_operations" if state == "needs_benefits_review" else "eligibility_operations",
            "next_action": action, "evidence": evidence, "trace": trace + [reason],
        }

    if http_status != 200:
        return result("needs_source", "transport_not_successful", "Obtain the source response; an outage is not a coverage decision.")
    trace.append("transport_arrived")
    if not isinstance(body, dict) or body.get("resourceType") != "CoverageEligibilityResponse":
        return result("needs_source", "wrong_resource_type", "Load the expected eligibility response, not another FHIR resource.")
    if has_modifier_extension(body):
        return result("needs_source", "unsupported_modifier", "Resolve the modifier's meaning in the approved profile before using this mapper.")
    if body.get("status") != "active":
        return result("needs_source", "resource_not_active", "Obtain a usable source record; its lifecycle status is not coverage status.")
    observed("status", body["status"], "This is the resource's lifecycle state, not the plan's coverage state.")
    if body.get("outcome") != "complete":
        return result("needs_source", "processing_not_complete", "Resolve processing coverage; this contract does not complete a handoff from a partial response.")
    observed("outcome", body["outcome"], "Processing is complete; no authorization approval is inferred.")
    purpose = body.get("purpose")
    if not isinstance(purpose, list) or "auth-requirements" not in purpose:
        return result("needs_source", "different_response_purpose", "Request the authorization-requirement information needed for this task.")
    for key in ("patient", "request", "insurer"):
        if reference(body, key) != getattr(question, key):
            return result("needs_source", "reference_mismatch", "Resolve the patient, request and payer mapping before reading a benefit fact.")
    if body.get("servicedDate") != question.service_date or "servicedPeriod" in body:
        return result("needs_source", "service_date_mismatch", "Recheck the requested date; periods require a separately agreed mapping.")
    trace.append("question_scope_matches")
    observed("servicedDate", body["servicedDate"], "The response addresses the exact date in this question.")

    insurance = body.get("insurance")
    if not isinstance(insurance, list) or any(not isinstance(plan, dict) for plan in insurance):
        return result("needs_source", "invalid_insurance_shape", "Obtain a readable insurance array for this teaching contract.")
    plans = [(i, plan) for i, plan in enumerate(insurance) if reference(plan, "coverage") == question.coverage]
    if len(plans) != 1:
        return result("needs_source", "coverage_not_unique", "Identify exactly one matching coverage record; do not take the first plan.")
    index, plan = plans[0]
    prefix = f"insurance[{index}]"
    inforce = plan.get("inforce")
    if type(inforce) is not bool:
        return result("needs_source", "coverage_unreported_or_invalid", "Keep coverage unknown until a boolean in-force observation is available.")
    observed(prefix + ".inforce", inforce, "The payer's in-force observation for this coverage and date.")
    if not inforce:
        return result("needs_benefits_review", "coverage_not_in_force", "Review the reported coverage state with benefits operations; do not decide care or claim payment.")

    items = plan.get("item", [])
    if not isinstance(items, list) or any(not isinstance(item, dict) for item in items):
        return result("needs_source", "invalid_item_shape", "Resolve the service-item structure with the source adapter.")

    def matches(item: dict) -> bool:
        service = item.get("productOrService")
        coding = service.get("coding") if isinstance(service, dict) else None
        return isinstance(coding, list) and any(
            isinstance(code, dict) and code.get("system") == question.code_system
            and code.get("code") == question.service_code for code in coding)

    selected = [(i, item) for i, item in enumerate(items) if matches(item)]
    if len(selected) != 1:
        return result("needs_source", "service_not_unique", "Identify one matching service code and namespace; do not select by display text.")
    item_index, item = selected[0]
    if "excluded" in item and type(item["excluded"]) is not bool:
        return result("needs_source", "invalid_exclusion_flag", "Resolve the source's exclusion flag without coercing its meaning.")
    if item.get("excluded") is True:
        return result("needs_benefits_review", "reported_service_exclusion", "Ask benefits operations to explain the reported exclusion; this is not a clinical or claim decision.")
    path = f"{prefix}.item[{item_index}].authorizationRequired"
    if "authorizationRequired" not in item:
        if not default_missing_to_false:
            observed(path, None, "The requirement was not supplied; absence is not false.")
            return result("needs_source", "requirement_unreported", "Obtain the missing requirement before drafting an affirmative statement.")
        required = False  # Deliberate teaching defect: inventing a negative answer.
        trace.append("missing_requirement_defaulted_to_false")
    else:
        required = item["authorizationRequired"]
    if type(required) is not bool:
        return result("needs_source", "invalid_requirement_flag", "Resolve the non-boolean value; do not use string truthiness.")
    observed(path, required, "A requirement flag, not an approval decision.")
    trace.append("matched_service_requirement")
    return result("reported", "authorization_required" if required else "authorization_not_required",
                  "Carry the exact source fact to staff; obtain approval, payment and patient-cost evidence separately.", required)


def scenarios() -> list[tuple[str, int, dict]]:
    cases: list[tuple[str, int, dict]] = []

    def add(name: str, change=None, status: int = 200) -> None:
        body = response()
        if change:
            change(body)
        cases.append((name, status, body))

    add("authorization-required")
    add("authorization-not-required", lambda r: r["insurance"][0]["item"][0].update(authorizationRequired=False))
    add("requirement-unreported", lambda r: r["insurance"][0]["item"][0].pop("authorizationRequired"))
    add("coverage-not-in-force", lambda r: r["insurance"][0].update(inforce=False))
    add("coverage-unreported", lambda r: r["insurance"][0].pop("inforce"))
    add("partial-response", lambda r: r.update(outcome="partial"))
    add("wrong-patient", lambda r: r["patient"].update(reference="Patient/SYNTHETIC-OTHER"))
    add("wrong-coverage", lambda r: r["insurance"][0]["coverage"].update(reference="Coverage/SYNTHETIC-OTHER"))
    add("wrong-service-code", lambda r: r["insurance"][0]["item"][0]["productOrService"]["coding"][0].update(code="SYNTHETIC-OTHER"))
    add("wrong-service-date", lambda r: r.update(servicedDate="2026-10-23"))
    add("ambiguous-coverage", lambda r: r["insurance"].append(deepcopy(r["insurance"][0])))
    add("ambiguous-service", lambda r: r["insurance"][0]["item"].append(deepcopy(r["insurance"][0]["item"][0])))
    add("cancelled-response", lambda r: r.update(status="cancelled"))
    add("transport-failure", status=503)
    add("matching-plan-second", lambda r: r["insurance"].insert(0, {"coverage": {"reference": "Coverage/SYNTHETIC-OTHER"}, "inforce": False}))
    return cases


def report(*, default_missing_to_false: bool = False, scenario: str | None = None) -> dict:
    question = Question()
    return {
        "synthetic": True, "fhir_version": "R4 / 4.0.1 teaching subset",
        "mode": "deliberately_broken_missing_default" if default_missing_to_false else "guarded",
        "question": asdict(question),
        "cases": [{"name": name, "http_status": status, "input": body,
                   "result": interpret(question, body, status, default_missing_to_false=default_missing_to_false)}
                  for name, status, body in scenarios() if scenario is None or name == scenario],
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--json", action="store_true")
    parser.add_argument("--default-missing-to-false", action="store_true", help="Deliberately invent false when the requirement is absent")
    parser.add_argument("--scenario", choices=[name for name, _, _ in scenarios()])
    args = parser.parse_args()
    data = report(default_missing_to_false=args.default_missing_to_false, scenario=args.scenario)
    if args.json:
        print(json.dumps(data, indent=2))
    else:
        print(f"SYNTHETIC FHIR ELIGIBILITY / {data['mode']} / no writes")
        for item in data["cases"]:
            result = item["result"]
            print(f"{item['name']:28} {result['state']:24} {result['reason']}")


if __name__ == "__main__":
    main()
