from synthneura.core.schemas import ClinicalTrial, LLMRawResponse
from synthneura.llm.base import LLMClient
from synthneura.services.extraction import extract_trial_facts


class _InvalidJsonClient(LLMClient):
    def extract_endpoints_biomarkers(self, prompt: str) -> LLMRawResponse:
        return LLMRawResponse(raw_json="not-json", model="gpt-test", provider="mock")


class _ValidJsonClient(LLMClient):
    def extract_endpoints_biomarkers(self, prompt: str) -> LLMRawResponse:
        return LLMRawResponse(
            raw_json='{"endpoints":[{"raw_text":"PFS","normalized_name":"PFS"}],'
            '"biomarkers":[{"raw_text":"ERBB1","normalized_name":"ERBB1"}]}',
            model="gpt-test",
            provider="mock",
        )


def _trial() -> ClinicalTrial:
    return ClinicalTrial(
        nct_id="NCT00000099",
        title="Test Trial",
        status="RECRUITING",
        phase="PHASE2",
        sponsor="Acme",
        conditions=["Condition A"],
        interventions=["Drug X"],
        outcomes=["Outcome 1"],
    )


def test_extract_trial_invalid_json_marks_validation_error():
    trial = _trial()
    result = extract_trial_facts(trial, _InvalidJsonClient())
    assert result.validation_status == "invalid"
    assert result.validation_errors
    assert "json_decode_error" in result.validation_errors[0]
    assert result.raw_response == "not-json"
    assert result.endpoints == []
    assert result.biomarkers == []


def test_extract_trial_normalizes_and_sets_metadata():
    trial = _trial()
    result = extract_trial_facts(trial, _ValidJsonClient())
    assert result.validation_status == "valid"
    assert result.prompt_version
    assert result.model == "gpt-test"
    assert result.provider == "mock"
    assert result.endpoints[0].normalized_name == "Progression-Free Survival (PFS)"
    assert result.biomarkers[0].normalized_name == "EGFR"
