"""Populates the SQLite DB with three demo tenants (hospital, real_estate, tourism)."""

import json

from app.db.database import Base, SessionLocal, engine
from app.db.fts import init_fts, rebuild_fts
from app.db.models import (
    Agent,
    Appointment,
    Department,
    Destination,
    Doctor,
    Faq,
    Lead,
    Package,
    Property,
    SiteVisit,
    Tenant,
)


def _tenants() -> list[Tenant]:
    return [
        Tenant(
            id="aarogya-hospital",
            name="Aarogya Multispecialty Hospital",
            vertical="hospital",
            bot_name="Aarogya Assistant",
            welcome_message="Hi! I'm your Aarogya Hospital assistant. I can help you find doctors, check availability, and answer hospital questions.",
            primary_color="#1f4bd8",
            position="right",
            quick_actions=json.dumps(["Find a doctor", "Book appointment", "Departments", "Hospital info"]),
        ),
        Tenant(
            id="skyline-realty",
            name="Skyline Realty",
            vertical="real_estate",
            bot_name="Skyline Assistant",
            welcome_message="Hi! I'm the Skyline Realty assistant. Ask me about properties, pricing, or schedule a site visit.",
            primary_color="#0da2a3",
            position="right",
            quick_actions=json.dumps(["Search properties", "Schedule a visit", "Talk to an agent", "FAQs"]),
        ),
        Tenant(
            id="wanderlust-tours",
            name="Wanderlust Tours & Travels",
            vertical="tourism",
            bot_name="Wanderlust Assistant",
            welcome_message="Hi! I'm the Wanderlust Tours assistant. Ask me about holiday packages, destinations, or pricing.",
            primary_color="#ea580c",
            position="right",
            quick_actions=json.dumps(["Browse packages", "Destinations", "Check price", "FAQs"]),
        ),
    ]


_SCHEDULE_DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]


def _make_schedule(weekend: bool = False, evening: bool = True, slot: int = 30) -> str:
    """Mirrors the original frontend `makeSchedule()`: Mon-Fri always on, Sat optional,
    Sun always off; either a morning+evening split or a single long morning session."""
    schedule = []
    for day in _SCHEDULE_DAYS:
        enabled = False if day == "sun" else (weekend if day == "sat" else True)
        sessions = (
            [{"start": "09:00", "end": "13:00"}, {"start": "17:00", "end": "20:00"}]
            if evening
            else [{"start": "09:00", "end": "14:00"}]
        )
        schedule.append({"day": day, "enabled": enabled, "slotDuration": slot, "sessions": sessions if enabled else []})
    return json.dumps(schedule)


def _hospital_data(tenant_id: str):
    departments = [
        Department(id="dp-1", tenant_id=tenant_id, name="Cardiology", description="Heart and cardiovascular care, diagnostics and interventions."),
        Department(id="dp-2", tenant_id=tenant_id, name="Orthopedics", description="Bones, joints, spine and sports injury treatment."),
        Department(id="dp-3", tenant_id=tenant_id, name="Neurology", description="Brain, spine and nervous system disorders."),
        Department(id="dp-4", tenant_id=tenant_id, name="Pediatrics", description="Comprehensive child and adolescent healthcare."),
        Department(id="dp-5", tenant_id=tenant_id, name="Dermatology", description="Skin, hair and nail conditions and cosmetic care."),
        Department(id="dp-6", tenant_id=tenant_id, name="Gynecology", description="Women's health, pregnancy and reproductive care."),
        Department(id="dp-7", tenant_id=tenant_id, name="ENT", description="Ear, nose and throat diagnosis and surgery."),
        Department(id="dp-8", tenant_id=tenant_id, name="General Medicine", description="Primary care, preventive health and diagnostics."),
    ]

    doctors = [
        Doctor(id="dr-1", tenant_id=tenant_id, name="Dr. Rahul Sharma", specialization="Interventional Cardiologist", department_id="dp-1", department_name="Cardiology", qualification="MBBS, MD, DM (Cardiology)", experience_years=16, languages="English,Hindi,Marathi", branch="Andheri West", consultation_fee=1200, rating=4.9, status="active", next_available="Today, 5:30 PM",
               bio="Dr. Rahul Sharma is a senior interventional cardiologist with over 16 years of experience in angioplasty, complex coronary interventions and preventive cardiology.", reviews=342, schedule_json=_make_schedule(weekend=True)),
        Doctor(id="dr-2", tenant_id=tenant_id, name="Dr. Ananya Iyer", specialization="Cardiac Electrophysiologist", department_id="dp-1", department_name="Cardiology", qualification="MBBS, MD, DM (Cardiology)", experience_years=11, languages="English,Hindi,Tamil", branch="Andheri West", consultation_fee=1000, rating=4.8, status="active", next_available="Tomorrow, 10:00 AM",
               bio="Dr. Ananya Iyer specializes in heart rhythm disorders, pacemaker implantation and cardiac electrophysiology studies with a patient-first approach to non-invasive care.", reviews=210, schedule_json=_make_schedule()),
        Doctor(id="dr-3", tenant_id=tenant_id, name="Dr. Meera Deshpande", specialization="Orthopedic Surgeon", department_id="dp-2", department_name="Orthopedics", qualification="MBBS, MS (Ortho)", experience_years=14, languages="English,Hindi,Marathi", branch="Andheri West", consultation_fee=1100, rating=4.8, status="active", next_available="Tomorrow, 11:30 AM",
               bio="Dr. Meera Deshpande is a joint replacement and sports injury specialist with expertise in minimally invasive arthroscopic surgery.", reviews=289, schedule_json=_make_schedule(weekend=True)),
        Doctor(id="dr-4", tenant_id=tenant_id, name="Dr. Arjun Kapoor", specialization="Spine Surgeon", department_id="dp-2", department_name="Orthopedics", qualification="MBBS, MS (Ortho), Fellowship (Spine)", experience_years=12, languages="English,Hindi,Punjabi", branch="Powai", consultation_fee=1300, rating=4.9, status="unavailable", next_available="Mon, 9:00 AM",
               bio="Dr. Arjun Kapoor specializes in complex spine surgery, disc replacement and scoliosis correction.", reviews=198, schedule_json=_make_schedule(evening=False)),
        Doctor(id="dr-5", tenant_id=tenant_id, name="Dr. Sanjay Menon", specialization="Neurologist", department_id="dp-3", department_name="Neurology", qualification="MBBS, MD, DM (Neurology)", experience_years=18, languages="English,Hindi,Malayalam", branch="Andheri West", consultation_fee=1400, rating=4.9, status="active", next_available="Today, 4:00 PM",
               bio="Dr. Sanjay Menon is a leading neurologist treating stroke, epilepsy, movement disorders and headache with 18 years of clinical experience.", reviews=415, schedule_json=_make_schedule()),
        Doctor(id="dr-6", tenant_id=tenant_id, name="Dr. Priya Ramanathan", specialization="Pediatrician", department_id="dp-4", department_name="Pediatrics", qualification="MBBS, MD (Pediatrics)", experience_years=10, languages="English,Hindi,Tamil", branch="Bandra East", consultation_fee=800, rating=4.9, status="active", next_available="Today, 3:30 PM",
               bio="Dr. Priya Ramanathan provides comprehensive newborn, child and adolescent care with special interest in childhood immunization and nutrition.", reviews=372, schedule_json=_make_schedule(weekend=True)),
        Doctor(id="dr-7", tenant_id=tenant_id, name="Dr. Kavita Rao", specialization="Dermatologist", department_id="dp-5", department_name="Dermatology", qualification="MBBS, MD (Dermatology)", experience_years=8, languages="English,Hindi,Kannada", branch="Bandra East", consultation_fee=900, rating=4.7, status="active", next_available="Today, 6:15 PM",
               bio="Dr. Kavita Rao treats a wide range of skin, hair and nail conditions with a focus on both medical and cosmetic dermatology.", reviews=156, schedule_json=_make_schedule()),
        Doctor(id="dr-8", tenant_id=tenant_id, name="Dr. Neha Joshi", specialization="Gynecologist", department_id="dp-6", department_name="Gynecology", qualification="MBBS, MD (OBG)", experience_years=13, languages="English,Hindi,Marathi", branch="Powai", consultation_fee=1000, rating=4.8, status="active", next_available="Tomorrow, 9:30 AM",
               bio="Dr. Neha Joshi offers comprehensive women's health care across pregnancy, fertility and reproductive wellness.", reviews=231, schedule_json=_make_schedule()),
        Doctor(id="dr-9", tenant_id=tenant_id, name="Dr. Rohan Verma", specialization="ENT Surgeon", department_id="dp-7", department_name="ENT", qualification="MBBS, MS (ENT)", experience_years=9, languages="English,Hindi", branch="Andheri West", consultation_fee=850, rating=4.6, status="active", next_available="Today, 2:00 PM",
               bio="Dr. Rohan Verma specializes in ear, nose and throat surgery, including sinus and hearing disorders.", reviews=178, schedule_json=_make_schedule(evening=False)),
        Doctor(id="dr-10", tenant_id=tenant_id, name="Dr. Sunita Pillai", specialization="General Physician", department_id="dp-8", department_name="General Medicine", qualification="MBBS, MD (Medicine)", experience_years=15, languages="English,Hindi,Malayalam", branch="Bandra East", consultation_fee=600, rating=4.7, status="active", next_available="Today, 1:00 PM",
               bio="Dr. Sunita Pillai provides primary care, preventive health checkups and chronic disease management for the whole family.", reviews=264, schedule_json=_make_schedule(weekend=True, evening=False)),
    ]

    faqs = [
        ("Visiting Hours", "What are your visiting hours?", "General visiting hours are 11 AM–1 PM and 5 PM–7 PM daily. ICU visiting is restricted to immediate family for 15 minutes twice a day."),
        ("Emergency", "What is the emergency contact number?", "Our 24x7 emergency helpline is +91 22 4890 1108. Please call this number or visit our Andheri West emergency entrance directly."),
        ("Insurance & Billing", "Do you accept health insurance?", "Yes, we are empaneled with most major insurers including cashless treatment for over 30 insurance providers. Please bring your insurance card and ID proof at admission."),
        ("Facilities", "Do you have parking available?", "Yes, all three branches (Andheri West, Bandra East, Powai) have dedicated visitor parking. Andheri West also offers valet parking."),
        ("Appointments", "How do I book an appointment?", "You can book an appointment through this chat by telling me the doctor or specialty you need, or by calling reception at +91 22 4890 1200."),
        ("Appointments", "Can I cancel or reschedule my appointment?", "Yes, appointments can be cancelled or rescheduled up to 2 hours before the slot via this chat or by calling reception."),
        ("Facilities", "Do you have an ambulance service?", "Yes, we operate a 24x7 ambulance service. Call the emergency helpline +91 22 4890 1108 for immediate dispatch."),
        ("Diagnostics", "Do you offer MRI and CT scan facilities?", "Yes, all branches have in-house MRI, CT scan, X-ray and ultrasound facilities with reports typically available within 24 hours."),
        ("Diagnostics", "Do you have a pathology lab?", "Yes, our NABL-accredited pathology lab is open 7 AM–9 PM daily, including home sample collection on request."),
        ("Facilities", "Do you have a blood bank?", "Yes, our Andheri West branch has an in-house licensed blood bank operating 24x7."),
        ("Services", "Do you offer teleconsultation?", "Yes, teleconsultation is available for follow-up consultations with most departments. Ask reception to set up a video consult."),
        ("Services", "What health checkup packages do you offer?", "We offer basic, executive and senior-citizen health checkup packages ranging from ₹1,500 to ₹6,000. Ask me for current package details."),
        ("Insurance & Billing", "What payment methods do you accept?", "We accept cash, all major cards, UPI, and net banking. EMI options are available for treatments above ₹50,000."),
        ("Hospital Information", "Where are your branches located?", "We have three branches in Mumbai: Andheri West (Link Road), Bandra East (Kalanagar) and Powai (Hiranandani Gardens)."),
        ("Physiotherapy", "Do you offer physiotherapy services?", "Yes, our physiotherapy and rehabilitation center is available at the Andheri West and Powai branches, open 8 AM–8 PM."),
    ]

    return departments, doctors, faqs


def _realestate_data(tenant_id: str):
    agents = [
        Agent(id="ag-1", tenant_id=tenant_id, name="Rohit Mehta", phone="+91 98200 11122", email="rohit@skylinerealty.in"),
        Agent(id="ag-2", tenant_id=tenant_id, name="Priyanka Shah", phone="+91 98200 33344", email="priyanka@skylinerealty.in"),
        Agent(id="ag-3", tenant_id=tenant_id, name="Karan Malhotra", phone="+91 98200 55566", email="karan@skylinerealty.in"),
    ]

    properties = [
        Property(id="pr-1", tenant_id=tenant_id, title="Sunrise Heights 2BHK", type="apartment", bhk=2, city="Mumbai", locality="Andheri West", price=8_500_000, area_sqft=850, amenities="gym,swimming pool,24x7 security,power backup", status="available", agent_id="ag-1", description="Well-ventilated 2BHK on the 8th floor with sea-facing balcony, modular kitchen, and covered parking."),
        Property(id="pr-2", tenant_id=tenant_id, title="Palm Residency 3BHK", type="apartment", bhk=3, city="Mumbai", locality="Powai", price=15_000_000, area_sqft=1250, amenities="clubhouse,swimming pool,gym,kids play area,security", status="available", agent_id="ag-2", description="Spacious 3BHK overlooking Powai lake, gated community with clubhouse and jogging track."),
        Property(id="pr-3", tenant_id=tenant_id, title="Green Valley 1BHK", type="apartment", bhk=1, city="Mumbai", locality="Mulund", price=5_200_000, area_sqft=520, amenities="security,power backup,lift", status="available", agent_id="ag-1", description="Compact and budget-friendly 1BHK, ideal for first-time buyers, close to Mulund station."),
        Property(id="pr-4", tenant_id=tenant_id, title="Ocean View Villa", type="villa", bhk=4, city="Mumbai", locality="Juhu", price=95_000_000, area_sqft=3200, amenities="private pool,garden,servant quarters,security", status="available", agent_id="ag-3", description="Luxury 4BHK villa near Juhu beach with private pool, landscaped garden, and 3 covered car parks."),
        Property(id="pr-5", tenant_id=tenant_id, title="Business Square Office", type="commercial", bhk=None, city="Mumbai", locality="BKC", price=32_000_000, area_sqft=1500, amenities="24x7 access,parking,cafeteria,security", status="available", agent_id="ag-2", description="Grade-A commercial office space in BKC, ready to move in, ideal for corporate offices."),
        Property(id="pr-6", tenant_id=tenant_id, title="Hillcrest 2BHK", type="apartment", bhk=2, city="Pune", locality="Baner", price=7_200_000, area_sqft=980, amenities="gym,swimming pool,clubhouse,security", status="available", agent_id="ag-3", description="Modern 2BHK in a premium Baner township with landscaped gardens and jogging track."),
        Property(id="pr-7", tenant_id=tenant_id, title="Riverside Plot", type="plot", bhk=None, city="Pune", locality="Wagholi", price=4_500_000, area_sqft=2400, amenities="gated layout,water connection,electricity", status="available", agent_id="ag-1", description="NA-approved residential plot in a gated layout, ready for construction, clear title."),
        Property(id="pr-8", tenant_id=tenant_id, title="Skyline Towers 3BHK", type="apartment", bhk=3, city="Pune", locality="Kharadi", price=11_800_000, area_sqft=1400, amenities="gym,swimming pool,clubhouse,kids play area,security", status="available", agent_id="ag-2", description="Premium 3BHK close to IT parks in Kharadi, with premium fittings and dedicated parking."),
        Property(id="pr-9", tenant_id=tenant_id, title="Lakeview 1BHK", type="apartment", bhk=1, city="Pune", locality="Hinjewadi", price=4_800_000, area_sqft=610, amenities="gym,security,power backup", status="sold", agent_id="ag-3", description="Cozy 1BHK near Hinjewadi IT park, currently sold — similar units available on request."),
        Property(id="pr-10", tenant_id=tenant_id, title="Marina Bay 2BHK", type="apartment", bhk=2, city="Mumbai", locality="Bandra East", price=13_500_000, area_sqft=900, amenities="gym,security,power backup,lift", status="available", agent_id="ag-1", description="Contemporary 2BHK in Bandra East, walking distance to BKC and the railway station."),
    ]

    faqs = [
        ("Documentation", "What documents are required to buy a property?", "You'll need identity proof (Aadhaar/PAN), address proof, income proof, and passport-size photos. For home loans, banks additionally ask for 6 months of bank statements and ITR."),
        ("Financing", "Do you offer home loan assistance?", "Yes, we partner with leading banks and NBFCs to help you get pre-approved home loans at competitive interest rates, typically 8–9% p.a."),
        ("Booking", "What is the booking amount for a property?", "The standard token/booking amount is 10% of the property value to block the unit, adjustable against the final payment."),
        ("Site Visits", "Can I schedule a site visit?", "Yes, tell me the property you're interested in and your preferred date/time and I'll get an agent to confirm your site visit."),
        ("Legal", "Are your projects RERA registered?", "Yes, all our listed projects are RERA registered. RERA registration numbers are shared in the agreement and available on request."),
        ("Pricing", "Is the listed price negotiable?", "Prices have some flexibility depending on the property and payment plan. Our agent can discuss the best offer during your site visit."),
        ("Financing", "What is the typical payment plan?", "Most projects offer a construction-linked plan (10% booking, staged payments per construction milestone) or a down-payment plan with a discount."),
        ("Resale", "Do you deal in resale properties?", "Yes, in addition to new listings, we also handle verified resale properties across Mumbai and Pune."),
        ("Legal", "Do you assist with property registration?", "Yes, our legal team assists with sale deed drafting, stamp duty calculation, and registration at the sub-registrar office."),
        ("Rental", "Do you help with renting out a property?", "Yes, we offer tenant sourcing, verification, and rental agreement drafting services for property owners."),
        ("Amenities", "What amenities are typically included?", "Most of our apartment projects include a gym, swimming pool, clubhouse, 24x7 security, and power backup — specific amenities vary by property."),
        ("Possession", "What is the possession timeline for under-construction properties?", "Possession timelines vary by project, typically 18–36 months from booking. Ask about a specific property for its exact timeline."),
        ("Contact", "How do I contact an agent directly?", "I can share the assigned agent's name and phone number for any property you're interested in — just ask."),
        ("Charges", "Are there any additional charges apart from the property price?", "Yes, additional charges typically include stamp duty (5–6%), registration fee (1%), GST (for under-construction), and society/maintenance deposit."),
        ("Inspection", "Can I get a property inspected before buying?", "Absolutely, we can arrange a physical inspection or a video walkthrough before you finalize the purchase."),
    ]

    return agents, properties, faqs


def _tourism_data(tenant_id: str):
    destinations = [
        Destination(id="ds-1", tenant_id=tenant_id, name="Goa", region="West India", best_time_to_visit="November–February", description="Beaches, nightlife, Portuguese heritage and water sports."),
        Destination(id="ds-2", tenant_id=tenant_id, name="Kerala Backwaters", region="South India", best_time_to_visit="September–March", description="Houseboat cruises, backwaters, Ayurveda and lush greenery."),
        Destination(id="ds-3", tenant_id=tenant_id, name="Manali", region="North India", best_time_to_visit="March–June, December–January", description="Snow-capped mountains, adventure sports and scenic valleys."),
        Destination(id="ds-4", tenant_id=tenant_id, name="Rajasthan", region="North India", best_time_to_visit="October–March", description="Royal palaces, forts, deserts and vibrant culture."),
        Destination(id="ds-5", tenant_id=tenant_id, name="Andaman Islands", region="Bay of Bengal", best_time_to_visit="October–May", description="Pristine beaches, scuba diving and coral reefs."),
        Destination(id="ds-6", tenant_id=tenant_id, name="Kashmir", region="North India", best_time_to_visit="March–October", description="Dal Lake, houseboats, gardens and snow-capped peaks."),
    ]

    packages = [
        Package(id="pk-1", tenant_id=tenant_id, title="Goa Beach Getaway", destination_id="ds-1", destination_name="Goa", duration_days=4, price=18_999, category="family", inclusions="3-star hotel,breakfast,airport transfers,sightseeing", rating=4.6),
        Package(id="pk-2", tenant_id=tenant_id, title="Goa Honeymoon Special", destination_id="ds-1", destination_name="Goa", duration_days=5, price=28_999, category="honeymoon", inclusions="4-star resort,candlelight dinner,breakfast+dinner,private transfers,couple spa", rating=4.8),
        Package(id="pk-3", tenant_id=tenant_id, title="Kerala Backwaters Bliss", destination_id="ds-2", destination_name="Kerala Backwaters", duration_days=5, price=24_999, category="family", inclusions="houseboat stay,resort stay,all meals,ayurveda session,transfers", rating=4.7),
        Package(id="pk-4", tenant_id=tenant_id, title="Manali Adventure Trip", destination_id="ds-3", destination_name="Manali", duration_days=6, price=21_999, category="adventure", inclusions="hotel stay,breakfast+dinner,paragliding,river rafting,transfers", rating=4.5),
        Package(id="pk-5", tenant_id=tenant_id, title="Rajasthan Royal Heritage Tour", destination_id="ds-4", destination_name="Rajasthan", duration_days=7, price=34_999, category="family", inclusions="heritage hotel stay,breakfast,guided fort tours,camel safari,transfers", rating=4.8),
        Package(id="pk-6", tenant_id=tenant_id, title="Andaman Island Escape", destination_id="ds-5", destination_name="Andaman Islands", duration_days=5, price=32_999, category="honeymoon", inclusions="beach resort,breakfast+dinner,scuba diving,island hopping,transfers", rating=4.7),
        Package(id="pk-7", tenant_id=tenant_id, title="Kashmir Paradise Tour", destination_id="ds-6", destination_name="Kashmir", duration_days=6, price=29_999, category="family", inclusions="houseboat+hotel stay,all meals,shikara ride,gulmarg gondola,transfers", rating=4.9),
        Package(id="pk-8", tenant_id=tenant_id, title="Char Dham Pilgrimage", destination_id="ds-6", destination_name="Kashmir", duration_days=8, price=26_999, category="pilgrimage", inclusions="hotel/dharamshala stay,all meals,transport,guide", rating=4.6),
    ]

    faqs = [
        ("Cancellation", "What is your cancellation policy?", "Cancellations made 15+ days before departure get a full refund minus a 10% processing fee. 7–14 days: 50% refund. Less than 7 days: non-refundable."),
        ("Payments", "What is the payment plan for booking a package?", "A 25% advance confirms your booking, with the balance due 15 days before departure. EMI options are available on select packages."),
        ("Visa", "Do you offer visa assistance?", "Yes, for international packages we provide end-to-end visa documentation assistance and appointment scheduling."),
        ("Customization", "Can I customize an itinerary?", "Yes, all our packages can be customized — extend your stay, add activities, or change hotel categories. Just tell me what you'd like to change."),
        ("Group Travel", "Do you offer group discounts?", "Yes, groups of 6 or more get a 10% discount, and groups of 10+ get a complimentary tour manager."),
        ("Inclusions", "What is typically included in the package price?", "Our packages typically include accommodation, meals as specified, airport/station transfers, and sightseeing as per itinerary. Flights are usually separate unless mentioned."),
        ("Inclusions", "Are flights included in the package price?", "Flights are not included by default in most packages, but we can add flight bookings for an additional cost — just ask."),
        ("Safety", "Is travel insurance included?", "Basic travel insurance is included for domestic packages. International packages require travel insurance which we can arrange for you."),
        ("Family Travel", "Are your packages suitable for families with kids?", "Yes, most packages are family-friendly, and children below 5 years typically travel free or at a discounted rate — ask about a specific package."),
        ("Solo Travel", "Do you have packages for solo travelers?", "Yes, we offer solo traveler packages with single-occupancy options; a single supplement charge applies."),
        ("Best Time", "When is the best time to visit Goa?", "The best time to visit Goa is November to February when the weather is pleasant and dry."),
        ("Documentation", "What documents do I need for domestic travel?", "A valid government photo ID (Aadhaar, passport, driving license or voter ID) is required for domestic travel and hotel check-in."),
        ("Health", "What precautions are needed for high-altitude destinations like Manali?", "We recommend acclimatization days, staying hydrated, and carrying basic altitude-sickness medication for high-altitude destinations."),
        ("Booking", "How far in advance should I book?", "We recommend booking at least 3–4 weeks in advance, and 2+ months for peak season (Dec–Jan, and international destinations)."),
        ("Support", "Is there a tour manager available during the trip?", "Yes, group packages include a dedicated tour manager. Individual/couple packages have 24x7 phone support instead."),
    ]

    return destinations, packages, faqs


def seed(reset: bool = True) -> None:
    Base.metadata.create_all(engine)
    init_fts(engine)

    db = SessionLocal()
    try:
        if reset:
            for model in [Appointment, SiteVisit, Lead, Package, Destination, Property, Agent, Doctor, Department, Faq, Tenant]:
                db.query(model).delete()
            db.commit()

        for tenant in _tenants():
            db.add(tenant)
        db.commit()

        dep, doc, hosp_faqs = _hospital_data("aarogya-hospital")
        db.add_all(dep)
        db.add_all(doc)
        db.add_all(Faq(tenant_id="aarogya-hospital", category=c, question=q, answer=a) for c, q, a in hosp_faqs)

        ag, prop, re_faqs = _realestate_data("skyline-realty")
        db.add_all(ag)
        db.add_all(prop)
        db.add_all(Faq(tenant_id="skyline-realty", category=c, question=q, answer=a) for c, q, a in re_faqs)

        dest, pkg, tour_faqs = _tourism_data("wanderlust-tours")
        db.add_all(dest)
        db.add_all(pkg)
        db.add_all(Faq(tenant_id="wanderlust-tours", category=c, question=q, answer=a) for c, q, a in tour_faqs)

        db.commit()
        rebuild_fts(db)
        print("Seed complete: aarogya-hospital, skyline-realty, wanderlust-tours")
    finally:
        db.close()


if __name__ == "__main__":
    seed()
