"""Tests for Patient extractors."""

import pytest

from fhir_agent_tools import get_patient_summary, get_patient_name, get_patient_identifiers


PATIENT_JSON = '''
{
  "resourceType": "Patient",
  "id": "example",
  "identifier": [{
    "use": "usual",
    "system": "urn:oid:1.2.36.146.595.217.0.1",
    "value": "12345"
  }],
  "name": [{
    "use": "official",
    "family": "Chalmers",
    "given": ["Peter", "James"]
  }],
  "gender": "male",
  "birthDate": "1974-12-25"
}
'''


def test_get_patient_summary_success():
    result = get_patient_summary(PATIENT_JSON)
    assert result["success"] is True
    data = result["data"]
    assert data["id"] == "example"
    assert data["name"] == "Chalmers, Peter James"
    assert data["birthDate"] == "1974-12-25"
    assert data["gender"] == "male"
    assert len(data["identifiers"]) == 1
    assert data["identifiers"][0]["value"] == "12345"


def test_get_patient_name():
    result = get_patient_name(PATIENT_JSON)
    assert result["success"] is True
    assert result["data"] == "Chalmers, Peter James"


def test_get_patient_identifiers():
    result = get_patient_identifiers(PATIENT_JSON)
    assert result["success"] is True
    assert len(result["data"]) == 1
    assert result["data"][0]["value"] == "12345"


def test_get_patient_empty_input():
    result = get_patient_summary("")
    assert result["success"] is False
    assert result["error"]["type"] == "empty_input"


def test_get_patient_invalid_json():
    result = get_patient_summary("not json")
    assert result["success"] is False
    assert result["error"]["type"] == "parse_error"


def test_get_patient_wrong_resource_type():
    obs_json = '{"resourceType": "Observation", "id": "x", "status": "final"}'
    result = get_patient_summary(obs_json)
    assert result["success"] is False
    assert result["error"]["type"] == "wrong_resource_type"


def test_get_patient_raise_on_error():
    from fhir_agent_tools import FhirExtractError

    with pytest.raises(FhirExtractError):
        get_patient_summary("", raise_on_error=True)

    data = get_patient_summary(PATIENT_JSON, raise_on_error=True)
    assert data["name"] == "Chalmers, Peter James"
