#!/usr/bin/env python3
"""Original FHIR R4 value-presence teaching fixture, Python 3.11+.
Synthetic Device Observations, no patient records, network, files or database.
Conservative authored consumer, not a general FHIR/profile/clinical validator.
"""
import argparse
import copy
import json
import platform
from decimal import Decimal

SYSTEM = "https://synthetic.example/fhir/CodeSystem/device-checks"
ABSENT_SYSTEM = "http://terminology.hl7.org/CodeSystem/data-absent-reason"
UCUM = "http://unitsofmeasure.org"
SUBJECT = "Device/SYNTHETIC-DEVICE-1"
CHOICES = ("valueQuantity", "valueCodeableConcept", "valueString", "valueBoolean", "valueInteger", "valueRange", "valueRatio", "valueSampledData", "valueTime", "valueDateTime", "valuePeriod")
CASES = ("boolean-false", "quantity-value", "reported-absence", "unexplained-missing", "null-value", "multiple-values", "value-and-absence", "preliminary", "entered-in-error", "wrong-choice", "wrong-unit", "quantity-comparator", "wrong-subject", "wrong-code")


def fixture(name, cycle_value):
    boolean_case = name in ("boolean-false", "reported-absence", "unexplained-missing", "null-value", "multiple-values", "value-and-absence")
    kind = "boolean" if boolean_case else "quantity"
    contract = {"subject": SUBJECT, "system": SYSTEM, "version": "1", "code": "self-check-passed" if boolean_case else "cycle-duration", "kind": kind}
    record = {"resourceType": "Observation", "id": "SYNTHETIC-OBS-" + name, "meta": {"versionId": "r2" if name == "quantity-value" and cycle_value == 1 else "r1"}, "status": "final", "subject": {"reference": SUBJECT}, "code": {"coding": [{"system": SYSTEM, "version": "1", "code": contract["code"], "display": "Synthetic self check" if boolean_case else "Synthetic cycle duration"}]}}
    quantity = {"value": cycle_value if name == "quantity-value" else 7, "unit": "seconds", "system": UCUM, "code": "s"}
    if boolean_case:
        record["valueBoolean"] = False
    else:
        record["valueQuantity"] = quantity
    if name in ("reported-absence", "unexplained-missing"):
        del record["valueBoolean"]
    if name in ("reported-absence", "value-and-absence"):
        record["dataAbsentReason"] = {"coding": [{"system": ABSENT_SYSTEM, "code": "not-performed"}]}
    if name == "null-value": record["valueBoolean"] = None
    if name == "multiple-values": record["valueQuantity"] = {**quantity, "value": 0}
    if name in ("preliminary", "entered-in-error"): record["status"] = name
    if name == "wrong-choice":
        del record["valueQuantity"]
        record["valueString"] = "0"
    if name == "wrong-unit": record["valueQuantity"]["code"] = "min"
    if name == "quantity-comparator": record["valueQuantity"]["comparator"] = "<"
    if name == "wrong-subject": record["subject"]["reference"] = "Device/SYNTHETIC-DEVICE-2"
    if name == "wrong-code": record["code"]["coding"][0]["code"] = "other-cycle"
    return json.dumps(record, sort_keys=True, separators=(",", ":")), contract


def interpret(record, contract):
    trace = []
    def result(state, reason, value=None, path=None):
        return {"state": state, "reason": reason, "value": value, "evidence_path": path, "trace": copy.deepcopy(trace)}
    if not isinstance(record, dict) or record.get("resourceType") != "Observation":
        return result("withheld", "not_supported_observation")
    if any(key in record for key in ("component", "hasMember", "derivedFrom", "extension", "modifierExtension")) or any(key.startswith("_") for key in record):
        return result("withheld", "uninterpreted_structure_or_extension")
    subject = record.get("subject")
    if not isinstance(subject, dict) or subject.get("reference") != contract["subject"]:
        return result("withheld", "subject_mismatch")
    code = record.get("code")
    codings = code.get("coding") if isinstance(code, dict) else None
    if not isinstance(codings, list) or len(codings) != 1 or not isinstance(codings[0], dict):
        return result("withheld", "coding_not_single")
    coding = codings[0]
    trace.append({"step": "code_identity", "observed": {k: coding.get(k) for k in ("system", "version", "code")}})
    if any(coding.get(key) != contract[key] for key in ("system", "version", "code")):
        return result("withheld", "coding_mismatch")
    present = [key for key in CHOICES if key in record]
    trace.append({"step": "presence", "present_value_keys": present, "data_absent_reason_present": "dataAbsentReason" in record})
    if any(key.startswith("value") and key not in CHOICES for key in record):
        return result("withheld", "unsupported_value_choice")
    if len(present) > 1:
        return result("withheld", "multiple_value_choices")
    if present and "dataAbsentReason" in record:
        return result("withheld", "value_and_absence_reason")
    if record.get("status") == "entered-in-error":
        return result("withheld", "entered_in_error")
    if record.get("status") != "final":
        return result("withheld", "status_not_admitted")
    if not present:
        if "dataAbsentReason" not in record:
            return result("no_value_reported", "absence_reason_not_supplied")
        absent = record["dataAbsentReason"]
        codes = absent.get("coding") if isinstance(absent, dict) else None
        if not isinstance(codes, list) or len(codes) != 1 or not isinstance(codes[0], dict) or codes[0].get("system") != ABSENT_SYSTEM or codes[0].get("code") != "not-performed":
            return result("withheld", "absence_reason_not_supported")
        return result("reported_absence", "not-performed", path="dataAbsentReason.coding[0]")
    field = present[0]
    raw = record[field]
    if raw is None:
        return result("withheld", "null_value_property")
    expected = "valueBoolean" if contract["kind"] == "boolean" else "valueQuantity"
    if field != expected:
        return result("withheld", "unexpected_value_choice")
    if field == "valueBoolean":
        if type(raw) is not bool:
            return result("withheld", "boolean_type_required")
        return result("supported_value", "explicit_boolean", {"kind": "boolean", "value": raw}, field)
    if not isinstance(raw, dict):
        return result("withheld", "quantity_object_required")
    if any(key.startswith("_") or key in ("extension", "modifierExtension") for key in raw):
        return result("withheld", "quantity_extension_not_supported")
    if "comparator" in raw:
        return result("withheld", "comparator_requires_policy")
    if raw.get("system") != UCUM or raw.get("code") != "s":
        return result("withheld", "unit_identity_mismatch")
    number = raw.get("value")
    if type(number) is not int and not isinstance(number, Decimal):
        return result("withheld", "json_number_required")
    exact = Decimal(number)
    if not exact.is_finite() or exact < 0 or exact > 1_000_000:
        return result("withheld", "number_outside_fixture_range")
    return result("supported_value", "explicit_quantity", {"kind": "quantity", "decimal": str(exact), "system": UCUM, "code": "s"}, "valueQuantity.value")


def broken_truthiness(record):
    quantity = record.get("valueQuantity")
    value = record.get("valueBoolean") or (quantity.get("value") if isinstance(quantity, dict) else None)
    return {"state": "present" if value else "missing", "value": str(value) if isinstance(value, Decimal) else value, "scope": "Deliberately ignores presence, status, source and units"}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--case", choices=CASES)
    parser.add_argument("--cycle-value", type=int, choices=(0, 1), default=0)
    args = parser.parse_args()
    reports = []
    for name in ([args.case] if args.case else CASES):
        raw, contract = fixture(name, args.cycle_value)
        record = json.loads(raw, parse_float=Decimal)
        before = copy.deepcopy(record)
        guarded = interpret(record, contract)
        broken = broken_truthiness(record)
        if record != before: raise RuntimeError("Original source record changed")
        reports.append({"case": name, "input_json": raw, "contract": contract, "guarded": guarded, "broken_truthiness": broken, "input_unchanged": True})
    print(json.dumps({"schema": "lockedin.fhir-value-lab/v1", "python": platform.python_version(), "fhir_release": "4.0.1", "cycle_value": args.cycle_value, "scope": "Synthetic Device Observations; no clinical interpretation, source fetch or complete FHIR validation", "cases": reports}, indent=2))


if __name__ == "__main__":
    main()
