import asyncio
import uuid
import bcrypt
from sqlalchemy import text
from app.db.engine import engine, AsyncSessionLocal, Base
import app.models  # ensures all models are registered with Base
from app.models.mstr_department import MstrDepartment
from app.models.mstr_question import MstrQuestion
from app.models.question_dept_map import QuestionDeptMap
from app.models.mstr_role import MstrRole
from app.models.user import User

# ── Fixed IDs — stable across every seed run ──────────────────────────────────
DEPT_ID             = uuid.UUID("11111111-1111-1111-1111-111111111111")
ADMIN_ID            = uuid.UUID("22222222-2222-2222-2222-222222222222")
PRIYA_ID            = uuid.UUID("33333333-3333-3333-3333-333333333333")
ADMIN_ROLE_ID       = uuid.UUID("44444444-4444-4444-4444-444444444444")
STAFF_ROLE_ID       = uuid.UUID("55555555-5555-5555-5555-555555555555")
SUPER_ADMIN_ID      = uuid.UUID("66666666-6666-6666-6666-666666666666")
SUPER_ADMIN_ROLE_ID = uuid.UUID("77777777-7777-7777-7777-777777777777")

CT_SURGERY_QUESTIONS = [
    {"id": uuid.UUID("aaaaaaaa-0001-0001-0001-000000000001"), "text": "What brings you in today?",                                                            "category": "CHIEF_COMPLAINT"},
    {"id": uuid.UUID("aaaaaaaa-0002-0002-0002-000000000002"), "text": "When did the symptoms start?",                                                         "category": "CHIEF_COMPLAINT"},
    {"id": uuid.UUID("aaaaaaaa-0003-0003-0003-000000000003"), "text": "Do you have chest pain? If yes — ask: is it sharp, dull, or pressure-like? Where is it located? Does it radiate to the arm or jaw? How long does it last? What triggers it?", "category": "CARDIAC"},
    {"id": uuid.UUID("aaaaaaaa-0004-0004-0004-000000000004"), "text": "Do you have shortness of breath? If yes — ask: is it at rest or only on exertion? How many steps before becoming breathless?", "category": "RESPIRATORY"},
    {"id": uuid.UUID("aaaaaaaa-0005-0005-0005-000000000005"), "text": "Do you have palpitations? If yes — ask: are they fast, irregular, or skipping beats?", "category": "CARDIAC"},
    {"id": uuid.UUID("aaaaaaaa-0006-0006-0006-000000000006"), "text": "Have you had any episodes of dizziness or fainting?",                                  "category": "CARDIAC"},
    {"id": uuid.UUID("aaaaaaaa-0007-0007-0007-000000000007"), "text": "Do you have leg or ankle swelling?",                                                   "category": "CARDIAC"},
    {"id": uuid.UUID("aaaaaaaa-0008-0008-0008-000000000008"), "text": "Do you feel unusually fatigued?",                                                      "category": "CARDIAC"},
    {"id": uuid.UUID("aaaaaaaa-0009-0009-0009-000000000009"), "text": "Do you wake up at night unable to breathe?",                                           "category": "CARDIAC"},
    {"id": uuid.UUID("aaaaaaaa-0010-0010-0010-000000000010"), "text": "Do you have difficulty breathing when lying flat?",                                    "category": "RESPIRATORY"},
    {"id": uuid.UUID("aaaaaaaa-0011-0011-0011-000000000011"), "text": "Do you have a cough? If yes — ask: is it dry or with phlegm? Any blood in the cough?", "category": "RESPIRATORY"},
    {"id": uuid.UUID("aaaaaaaa-0012-0012-0012-000000000012"), "text": "Do you have wheezing?",                                                                "category": "RESPIRATORY"},
    {"id": uuid.UUID("aaaaaaaa-0013-0013-0013-000000000013"), "text": "Do you have any previous heart conditions such as heart attack, heart failure, valve disease, or irregular heart rhythm?", "category": "HISTORY"},
    {"id": uuid.UUID("aaaaaaaa-0014-0014-0014-000000000014"), "text": "Do you have any previous lung conditions such as COPD, asthma, TB, or pneumonia?",    "category": "HISTORY"},
    {"id": uuid.UUID("aaaaaaaa-0015-0015-0015-000000000015"), "text": "Have you had any prior cardiac or thoracic surgeries?",                                "category": "HISTORY"},
    {"id": uuid.UUID("aaaaaaaa-0016-0016-0016-000000000016"), "text": "Do you have hypertension?",                                                            "category": "HISTORY"},
    {"id": uuid.UUID("aaaaaaaa-0017-0017-0017-000000000017"), "text": "Do you have diabetes?",                                                                "category": "HISTORY"},
    {"id": uuid.UUID("aaaaaaaa-0018-0018-0018-000000000018"), "text": "Do you have high cholesterol?",                                                        "category": "HISTORY"},
    {"id": uuid.UUID("aaaaaaaa-0019-0019-0019-000000000019"), "text": "Do you have any kidney problems?",                                                     "category": "HISTORY"},
    {"id": uuid.UUID("aaaaaaaa-0020-0020-0020-000000000020"), "text": "Is there any history of heart disease in the family?",                                 "category": "FAMILY_HISTORY"},
    {"id": uuid.UUID("aaaaaaaa-0021-0021-0021-000000000021"), "text": "Has there been any sudden cardiac death in the family?",                               "category": "FAMILY_HISTORY"},
    {"id": uuid.UUID("aaaaaaaa-0022-0022-0022-000000000022"), "text": "What medications are you currently taking? (especially blood thinners, beta blockers, diuretics)", "category": "MEDICATIONS"},
    {"id": uuid.UUID("aaaaaaaa-0023-0023-0023-000000000023"), "text": "Do you have any known allergies?",                                                     "category": "HISTORY"},
    {"id": uuid.UUID("aaaaaaaa-0024-0024-0024-000000000024"), "text": "Do you smoke or have a history of smoking? If yes — ask: current or past? How many years? How many per day?", "category": "LIFESTYLE"},
    {"id": uuid.UUID("aaaaaaaa-0025-0025-0025-000000000025"), "text": "Do you consume alcohol?",                                                              "category": "LIFESTYLE"},
    {"id": uuid.UUID("aaaaaaaa-0026-0026-0026-000000000026"), "text": "What is your exercise tolerance? How much activity before symptoms appear?",           "category": "LIFESTYLE"},
    {"id": uuid.UUID("aaaaaaaa-0027-0027-0027-000000000027"), "text": "Have you had any previous ECG, echocardiogram, or angiography done?",                  "category": "INVESTIGATIONS"},
    {"id": uuid.UUID("aaaaaaaa-0028-0028-0028-000000000028"), "text": "Do you have any known coronary artery disease or valve problems?",                     "category": "INVESTIGATIONS"},
]


def hash_pin(plain: str) -> str:
    return bcrypt.hashpw(plain.encode("utf-8"), bcrypt.gensalt(rounds=12)).decode("utf-8")


async def seed():
    # Wipe schema completely (handles old tables/constraints not in current metadata)
    async with engine.begin() as conn:
        await conn.execute(text("DROP SCHEMA public CASCADE"))
        await conn.execute(text("CREATE SCHEMA public"))
        await conn.run_sync(Base.metadata.create_all)
    print("Tables ready.")

    async with AsyncSessionLocal() as db:

        # ── Department ────────────────────────────────────────────────────────
        department = MstrDepartment(
            id=DEPT_ID,
            name="Cardio Thoracic Surgery",
            code="CTS-01",
            llm_system_prompt=(
                "You are a clinical intake assistant supporting Doctor's Staff in a Cardio Thoracic Surgery department.\n\n"
                "You do not speak to the patient directly. The Doctor's Staff reads your question aloud to the patient "
                "and relays the patient's answer back to you as transcribed text.\n\n"
                "Go through every question in the standard question bank one by one in order. "
                "For questions that have sub-questions embedded, ask the main question first. "
                "If the answer is YES, ask all sub-questions before moving on. "
                "If the answer is NO, move directly to the next main question.\n\n"
                "CRITICAL — Sub-question rule: NEVER ask a sub-question unless the main question for that topic "
                "has already been explicitly answered YES in this conversation. "
                "Example: NEVER ask 'Is the cough dry or with phlegm?' unless 'Does the patient have a cough?' "
                "was explicitly answered YES. NEVER ask 'Where is the chest pain located?' unless "
                "'Does the patient have chest pain?' was explicitly answered YES.\n\n"
                "IMPORTANT — Avoid redundant questions: Before asking each question from the standard list, "
                "carefully scan ALL previous answers in the conversation history. "
                "Before asking a question, check if its core information is already present anywhere in the conversation history. "
                "If the answer to any prior question already contains that information — even as part of a longer answer — treat it as covered and skip it. "
                "Do NOT ask a question just because it has not been asked yet; ask only if the information is genuinely missing from the conversation. "
                "Always check every unanswered question against the full history before deciding what to ask next.\n\n"
                "After all standard questions are covered, review the full conversation and ask any additional "
                "clinical follow-up questions your judgment suggests. "
                "When fully satisfied, return exactly: INTAKE_COMPLETE\n\n"
                "Rules: Ask one question at a time. Never diagnose. Never recommend treatment. "
                "Never address the patient directly. Always respond in English."
            ),
            llm_summary_prompt=(
                "You are a clinical documentation assistant for a cardiothoracic surgery department. "
                "Given a patient's intake conversation, generate a structured clinical summary.\n\n"
                "Return ONLY a valid JSON object with exactly these keys:\n\n"
                "{\n"
                '  "chiefComplaint": "Primary reason for visit in patient\'s own words",\n'
                '  "cardiacSymptoms": "Chest pain, breathlessness, palpitations, syncope, leg swelling, fatigue, orthopnea — include onset, severity, triggers, character for each reported symptom",\n'
                '  "respiratorySymptoms": "Cough, wheezing — include character and associated features",\n'
                '  "medicalHistory": "Prior cardiac/lung conditions, previous surgeries, hypertension, diabetes, cholesterol, kidney problems",\n'
                '  "familyHistory": "Family history of heart disease or sudden cardiac death",\n'
                '  "currentMedicationsAndAllergies": "Current medications with dosages and known allergies",\n'
                '  "lifestyle": "Smoking history, alcohol use, exercise tolerance",\n'
                '  "priorInvestigations": "Previous ECG, echocardiogram, angiography, known CAD or valve problems",\n'
                '  "additionalNotes": "Any contradictions, gaps, or clinically significant observations not captured above"\n'
                "}\n\n"
                "Rules:\n"
                "- Use clinical terminology appropriate for a senior physician\n"
                "- If a section has no data from the conversation, set its value to an empty string\n"
                "- Do NOT diagnose — describe findings only\n"
                "- Return ONLY the JSON object — no markdown, no extra text, no code fences"
            ),
            is_active=True,
        )
        db.add(department)
        await db.flush()

        # ── Questions + Department mapping ────────────────────────────────────
        for seq, q in enumerate(CT_SURGERY_QUESTIONS, start=1):
            question = MstrQuestion(
                id=q["id"],
                text=q["text"],
                category=q["category"],
                is_active=True,
            )
            db.add(question)
            await db.flush()

            mapping = QuestionDeptMap(
                question_id=q["id"],
                department_id=DEPT_ID,
                sequence_number=seq,
                is_active=True,
            )
            db.add(mapping)

        await db.flush()

        # ── Roles ─────────────────────────────────────────────────────────────
        super_admin_role = MstrRole(id=SUPER_ADMIN_ROLE_ID, name="Super Admin", role_key="SUPER_ADMIN")
        db.add(super_admin_role)

        admin_role = MstrRole(id=ADMIN_ROLE_ID, name="Admin", role_key="ADMIN")
        db.add(admin_role)

        staff_role = MstrRole(id=STAFF_ROLE_ID, name="Medical Staff", role_key="CONSULTANT")
        db.add(staff_role)

        await db.flush()

        # ── Super Admin ───────────────────────────────────────────────────────
        super_admin = User(
            id=SUPER_ADMIN_ID,
            department_id=DEPT_ID,
            name="Super Admin",
            email="superadmin@hospital.com",
            pin_hash=hash_pin("111111"),
            role_id=SUPER_ADMIN_ROLE_ID,
            is_active=True,
            failed_pin_attempts=0,
            locked_at=None,
        )
        db.add(super_admin)

        # ── Admin ─────────────────────────────────────────────────────────────
        admin = User(
            id=ADMIN_ID,
            department_id=DEPT_ID,
            name="Admin",
            email="admin@hospital.com",
            pin_hash=hash_pin("123456"),
            role_id=ADMIN_ROLE_ID,
            is_active=True,
            failed_pin_attempts=0,
            locked_at=None,
        )
        db.add(admin)

        # ── Dr. Priya Sharma ──────────────────────────────────────────────────
        priya = User(
            id=PRIYA_ID,
            department_id=DEPT_ID,
            name="Dr. Priya Sharma",
            email="priya@hospital.com",
            pin_hash=hash_pin("456789"),
            role_id=STAFF_ROLE_ID,
            is_active=True,
            failed_pin_attempts=0,
            locked_at=None,
        )
        db.add(priya)

        await db.commit()

        print("=" * 50)
        print("SEED COMPLETE")
        print("=" * 50)
        print(f"Department ID : {DEPT_ID}")
        print(f"Department    : Cardio Thoracic Surgery")
        print(f"Questions     : {len(CT_SURGERY_QUESTIONS)} inserted into mstr_question + question_dept_map")
        print()
        print(f"Super Admin — email: superadmin@hospital.com  | PIN: 111111")
        print(f"Admin       — email: admin@hospital.com       | PIN: 123456")
        print(f"Priya       — email: priya@hospital.com       | PIN: 456789")
        print("=" * 50)


asyncio.run(seed())
