"""Find-or-create helpers that normalize doctor/health-entity/medication names
extracted by the LLM into shared catalog rows, so analytics can count occurrences
across documents instead of treating every spelling as a new entity.

This is intentionally simple (case/whitespace normalization only). Real-world
name variants ("Dr. Juan Pérez" vs "Juan Perez Gómez") will still create
duplicates — upgrading to fuzzy matching is noted as future work in the README.
"""
from app.extensions import db
from app.models import Doctor, HealthEntity, Medication


def _normalize(value: str) -> str:
    return " ".join(value.strip().lower().split())


def get_or_create_doctor(full_name: str, license_number: str = None, specialty: str = None):
    if not full_name or not full_name.strip():
        return None

    normalized = _normalize(full_name)
    query = Doctor.query.filter_by(normalized_name=normalized)
    if license_number:
        by_license = Doctor.query.filter_by(license_number=license_number).first()
        if by_license:
            return by_license

    doctor = query.first()
    if doctor:
        if specialty and not doctor.specialty:
            doctor.specialty = specialty
        if license_number and not doctor.license_number:
            doctor.license_number = license_number
        return doctor

    doctor = Doctor(
        full_name=full_name.strip(),
        normalized_name=normalized,
        license_number=license_number or None,
        specialty=specialty or None,
    )
    db.session.add(doctor)
    db.session.flush()
    return doctor


def get_or_create_health_entity(name: str, entity_type: str = "other"):
    if not name or not name.strip():
        return None

    normalized = _normalize(name)
    entity = HealthEntity.query.filter_by(normalized_name=normalized).first()
    if entity:
        return entity

    entity = HealthEntity(
        name=name.strip(),
        normalized_name=normalized,
        entity_type=entity_type if entity_type in HealthEntity.TYPES else "other",
    )
    db.session.add(entity)
    db.session.flush()
    return entity


def get_or_create_medication(generic_name: str, brand_name: str = None, manufacturer_lab: str = None):
    if not generic_name or not generic_name.strip():
        return None

    normalized = _normalize(generic_name)
    medication = Medication.query.filter_by(normalized_generic_name=normalized).first()
    if medication:
        if brand_name and not medication.brand_name:
            medication.brand_name = brand_name
        if manufacturer_lab and not medication.manufacturer_lab:
            medication.manufacturer_lab = manufacturer_lab
        return medication

    medication = Medication(
        generic_name=generic_name.strip(),
        normalized_generic_name=normalized,
        brand_name=brand_name or None,
        manufacturer_lab=manufacturer_lab or None,
    )
    db.session.add(medication)
    db.session.flush()
    return medication
