"""One-off script: seeds realistic-looking demo data (WITHOUT calling the real
Claude API) so the app can be demoed end-to-end. Not part of the product —
delete instance/memodoc.db to wipe it, this is purely for a local walkthrough.
"""
import os
import random
import sys
from datetime import date, timedelta

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app
from app.extensions import db
from app.models import User, Patient, CaregiverLink, Document, MedicalEvent, Summary
from app.processing.entities import get_or_create_doctor, get_or_create_health_entity, get_or_create_medication

app = create_app()

DOCTORS = [
    ("Dra. Ana Martínez", "MP10234", "Endocrinología", "Clínica Vida Bogotá"),
    ("Dr. Carlos Restrepo", "MP20981", "Cardiología", "Hospital San Rafael"),
    ("Dra. Lucía Fernández", "MP30456", "Medicina General", "Clínica Vida Bogotá"),
    ("Dr. Jorge Salazar", "MP40877", "Neumología", "EPS Sura"),
]

ENTITIES = [
    ("Clínica Vida Bogotá", "clinic", "Colombia", "Bogotá"),
    ("Hospital San Rafael", "hospital", "Colombia", "Medellín"),
    ("EPS Sura", "insurer", "Colombia", "Bogotá"),
]

MEDICATIONS = [
    ("Metformina", "Glucophage", "Laboratorios Merck"),
    ("Losartán", "Cozaar", "Laboratorios MSD"),
    ("Salbutamol", "Ventolin", "GlaxoSmithKline"),
    ("Atorvastatina", "Lipitor", "Pfizer"),
    ("Levotiroxina", "Eutirox", "Merck"),
]

CONDITIONS = [
    ("Endocrino/Metabólico", "Diabetes tipo 2"),
    ("Cardiovascular", "Hipertensión arterial"),
    ("Respiratorio", "Asma bronquial"),
    ("Endocrino/Metabólico", "Hipotiroidismo"),
    ("Cardiovascular", "Dislipidemia"),
]

# (email, [(full_name, birth_date, country, city, relationship_type), ...])
# The last account (andres.demo@) is the showcase: one caregiver managing two
# profiles — himself and his elderly mother — the core use case of the product.
ACCOUNTS = [
    ("maria.demo@example.com", [("María Gómez", date(1985, 3, 12), "Colombia", "Bogotá", "self")]),
    ("pedro.demo@example.com", [("Pedro Sánchez", date(1962, 7, 22), "Colombia", "Medellín", "self")]),
    ("laura.demo@example.com", [("Laura Torres", date(1995, 11, 3), "México", "CDMX", "self")]),
    ("camila.demo@example.com", [("Camila Ortiz", date(1954, 9, 18), "Colombia", "Cali", "self")]),
    ("andres.demo@example.com", [
        ("Andrés Ríos", date(1978, 1, 30), "Perú", "Lima", "self"),
        ("Rosa Ríos", date(1943, 5, 9), "Perú", "Lima", "hijo_a"),
    ]),
]


def _seed_patient(user, full_name, birth_date, country, city, relationship_type):
    patient = Patient(
        created_by_user_id=user.id, full_name=full_name, birth_date=birth_date,
        phone="+57300" + str(random.randint(1000000, 9999999)), country=country, city=city,
        emergency_token=Patient.generate_emergency_token(),
        emergency_contact_name="Contacto de emergencia demo",
        emergency_contact_phone="+573001234567",
        blood_type=random.choice(["O+", "A+", "A-", "B+", "O-"]),
    )
    db.session.add(patient)
    db.session.flush()

    db.session.add(CaregiverLink(
        user_id=user.id, patient_id=patient.id,
        relationship_type=relationship_type, is_primary=True,
    ))

    for _ in range(random.randint(2, 4)):
        doc = Document(
            patient_id=patient.id, original_filename="receta_demo.pdf",
            storage_path="/tmp/demo.pdf", mime_type="application/pdf",
            status=Document.STATUS_DONE,
        )
        db.session.add(doc)
        db.session.flush()

        doctor_name, license_no, specialty, entity_name = random.choice(DOCTORS)
        entity_type = next(t for n, t, c, ci in ENTITIES if n == entity_name)
        doctor = get_or_create_doctor(doctor_name, license_number=license_no, specialty=specialty)
        entity = get_or_create_health_entity(entity_name, entity_type=entity_type)
        if doctor and entity and not doctor.health_entity_id:
            doctor.health_entity_id = entity.id

        category, description = random.choice(CONDITIONS)
        event_date = date.today() - timedelta(days=random.randint(10, 700))
        age_at_event = patient.age_at(event_date)

        db.session.add(MedicalEvent(
            patient_id=patient.id, document_id=doc.id, event_type="diagnosis",
            description=description, event_date=event_date, condition_category=category,
            patient_age_at_event=age_at_event, doctor=doctor, health_entity=entity,
        ))

        generic, brand, manufacturer = random.choice(MEDICATIONS)
        medication = get_or_create_medication(generic, brand_name=brand, manufacturer_lab=manufacturer)
        db.session.add(MedicalEvent(
            patient_id=patient.id, document_id=doc.id, event_type="medication",
            description=f"{generic} — dosis según indicación médica", event_date=event_date,
            patient_age_at_event=age_at_event, doctor=doctor, health_entity=entity, medication=medication,
        ))

    db.session.add(Summary(
        patient_id=patient.id, version=1,
        content=(
            f"Resumen de historia médica de {full_name}.\n\n"
            f"Diagnósticos activos: {CONDITIONS[0][1]}.\n"
            f"Medicamentos actuales: {MEDICATIONS[0][0]} ({MEDICATIONS[0][1]}).\n"
            "Antecedentes relevantes: sin hospitalizaciones registradas.\n"
        ),
    ))
    return patient


def main():
    with app.app_context():
        if User.query.filter_by(email="admin@memodoc.demo").first():
            print("Demo data already seeded, skipping.")
            return

        admin = User(email="admin@memodoc.demo", role="admin")
        admin.set_password("Demo12345!")
        db.session.add(admin)

        for email, profiles in ACCOUNTS:
            user = User(email=email, role="patient")
            user.set_password("Demo12345!")
            db.session.add(user)
            db.session.flush()

            for full_name, birth_date, country, city, relationship_type in profiles:
                _seed_patient(user, full_name, birth_date, country, city, relationship_type)

        db.session.commit()
        print("Demo data seeded: 1 admin + 5 caregiver accounts (one managing 2 profiles).")
        print("Admin login: admin@memodoc.demo / Demo12345!")
        print("Patient login example: maria.demo@example.com / Demo12345!")
        print("Caregiver-with-2-profiles login: andres.demo@example.com / Demo12345!")


if __name__ == "__main__":
    main()
