from typing import List

from synthneura.core.schemas import ClinicalTrial, ExtractedTrialData
from synthneura.llm.base import LLMClient


def _build_prompt(trial: ClinicalTrial) -> str:
    """
    Build a concise prompt from normalized trial fields.

    The prompt is optimized for endpoint and biomarker extraction.
    """

    parts: List[str] = []
    if trial.title:
        parts.append(f"Title: {trial.title}")
    if trial.conditions:
        parts.append(f"Conditions: {', '.join(trial.conditions)}")
    if trial.interventions:
        parts.append(f"Interventions: {', '.join(trial.interventions)}")
    if trial.outcomes:
        parts.append(f"Outcomes: {', '.join(trial.outcomes)}")
    content = "\n".join(parts)
    return (
        "Extract trial endpoints and biomarkers from the text below. "
        "Return JSON with keys: endpoints (list of strings), "
        "biomarkers (list of strings).\n\n"
        f"{content}"
    )


def extract_trial_facts(
    trial: ClinicalTrial,
    client: LLMClient,
) -> ExtractedTrialData:
    """
    Run LLM extraction for a single trial and return structured facts.
    """

    prompt = _build_prompt(trial)
    return client.extract_endpoints_biomarkers(prompt)
