import json
import re
from werkzeug.security import generate_password_hash
from utils.db import open_connection, run_migrations


def slugify(text: str) -> str:
    s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
    return s or "item"


DEFAULT_SETTINGS = [
    ("store_name", "DIECAST WORLD INDIA", "text", "Store display name"),
    ("store_tagline", "COLLECT • CONNECT • CELEBRATE", "text", "Header sub-tagline"),
    ("store_logo", "/static/assets/images/logo.png", "image", "Store logo path"),
    ("announcement_pill", "We are UP AND READY!", "text", "Announcement strip badge"),
    (
        "announcement_text",
        "DIECAST WORLD INDIA STORE IS OPEN & READY TO SERVE YOU! • Mumbai Collector Hub",
        "text",
        "Announcement strip main message",
    ),
    ("owner_name", "Priyal Shah", "text", "Store owner name"),
    ("contact_phone", "+91 96996 76722", "text", "Primary customer support phone"),
    ("secondary_phone", "+91 96996 76722", "text", "Secondary / WhatsApp phone"),
    ("contact_email", "diecastworldindia@gmail.com", "text", "Official store email"),
    (
        "store_address",
        "12, 1st Floor, Jai Kisan CHS, Plot No.296, Pantnagar, Ghatkopar (East), Mumbai - 400075",
        "text",
        "Physical hub address",
    ),
    (
        "instagram_url",
        "https://www.instagram.com/diecast_world_india?fqnt=aHRmdTl0azZ4NzJl",
        "text",
        "Official Instagram URL",
    ),
    ("instagram_handle", "@diecast_world_india", "text", "Instagram handle"),
    ("upi_id", "9022676722@okaxis", "text", "Manual UPI ID for order payments"),
    ("upi_payee_name", "Diecast World India", "text", "UPI payee display name"),
    ("upi_qr_image", "", "image", "Custom uploaded UPI QR code image (blank uses dynamic store QR)"),
    (
        "upi_instructions",
        "Pay the exact payable total using any UPI app or QR code above, then upload your payment screenshot and enter the 12-digit UTR/reference number. Orders remain in Payment Verification Pending until verified by admin.",
        "text",
        "Manual UPI payment instructions",
    ),
    ("shipping_charge_paise", "9900", "integer", "Standard flat shipping charge in paise (₹99)"),
    ("free_shipping_threshold_paise", "99900", "integer", "Free shipping order threshold in paise (₹999)"),
    ("garage_dispatch_fee_paise", "9900", "integer", "Consolidated Garage dispatch fee in paise (₹99)"),
    ("garage_free_dispatch_threshold_paise", "199900", "integer", "Free consolidated Garage dispatch threshold in paise"),
    ("garage_hold_days", "60", "integer", "Default Collector Garage Hold duration in days"),
    (
        "packaging_heading",
        "How Your Diecast Models Are Packed",
        "text",
        "Packaging section heading",
    ),
    (
        "packaging_subheading",
        "We know the heartbreak of cracked blister bubbles, bent card hangers, and cracked acrylic cases. Here is our 5-layer guarantee:",
        "text",
        "Packaging section subtitle",
    ),
    (
        "footer_about",
        "India's dedicated collector destination for premium 1:64, 1:43, and 1:18 scale diecast models. Featuring authorized Mini GT, Kaido House, Pop Race, Inno64, and RLC collectibles.",
        "text",
        "Footer about paragraph",
    ),
    ("footer_copyright", "© 2026 Diecast World India. All rights reserved. Designed for Indian Collectors.", "text", "Footer copyright text"),
]

BRANDS = [
    ("Mini GT", "mini-gt", "TSM Model Mini GT precision 1:64 scale collectibles", 1),
    ("Kaido House", "kaido-house", "Kaido House x Mini GT custom JDM & street machines", 2),
    ("Pop Race", "pop-race", "Pop Race detailed 1:64 with opening panels", 3),
    ("Inno64", "inno64", "Inno64 touring & race-spec 1:64 models in acrylic display cases", 4),
    ("Hot Wheels", "hot-wheels", "Hot Wheels RLC Exclusive & Car Culture Premiums", 5),
    ("Tarmac Works", "tarmac-works", "Tarmac Works GT3, Le Mans & Nurburgring scale models", 6),
    ("Almost Real", "almost-real", "Almost Real heavyweight licensed scale models", 7),
    ("Bburago", "bburago", "Bburago Signature licensed supercar models", 8),
    ("Solido", "solido", "Solido 1:18 centerpiece diecast cars", 9),
    ("Accessories", "accessories", "Dioramas, LED display garages & blister card protectors", 10),
]

EXTRA_BRANDS = [
    ("Hot Wheels Premium", "hot-wheels-premium", "Hot Wheels Premium collectible diecast series", "/static/assets/images/shop_models/Hot_Wheels_Premium.png", 20),
    ("Ignition Model", "ignition-model", "Ignition Model resin & precision scale collectibles", "/static/assets/images/shop_models/Ignition_Model.png", 21),
    ("BBR Models", "bbr-models", "BBR Models Italian luxury scale collectibles", "/static/assets/images/shop_models/BBR_MODELS.png", 22),
    ("Spark", "spark", "Spark Motorsport & Le Mans precision models", "/static/assets/images/shop_models/Spark.png", 23),
    ("CM Model", "cm-model", "CM Model 1:64 detailed diecast collectibles", "/static/assets/images/shop_models/CM_MODEL.png", 24),
    ("Time Micro", "time-micro", "Time Micro custom & livery 1:64 diecast models", "/static/assets/images/shop_models/Time_Micro.png", 25),
    ("LCD Models", "lcd-models", "LCD Models licensed multi-opening scale cars", "/static/assets/images/shop_models/LCD_Models.png", 26),
    ("7CM Model", "7cm-model", "7CM Model scale collectibles", "/static/assets/images/shop_models/7CM_Model.png", 30),
    ("97M", "97m", "97M scale collectibles", "/static/assets/images/shop_models/97M.png", 31),
    ("AirLines", "airlines", "AirLines collector series", "/static/assets/images/shop_models/AirLines.png", 32),
    ("Art of Craftsmanship", "art-of-craftsmanship", "Art of Craftsmanship scale collectibles", "/static/assets/images/shop_models/Art_of_Craftsmanship.png", 33),
    ("ATS Models", "ats-models", "ATS Models scale collectibles", "/static/assets/images/shop_models/ATS_Models.png", 34),
    ("Aurora Model", "aurora-model", "Aurora Model scale collectibles", "/static/assets/images/shop_models/Aurora_Model.png", 35),
    ("Banana Models", "banana-models", "Banana Models scale collectibles", "/static/assets/images/shop_models/Banana_Models.png", 36),
    ("BMC", "bmc", "BMC scale collectibles", "/static/assets/images/shop_models/BMC.png", 37),
    ("Cool Car", "cool-car", "Cool Car scale collectibles", "/static/assets/images/shop_models/Cool_Car.png", 38),
    ("D Model", "d-model", "D Model scale collectibles", "/static/assets/images/shop_models/D_Model.png", 39),
    ("DCT", "dct", "DCT scale collectibles", "/static/assets/images/shop_models/DCT.png", 40),
    ("Demon King Auto", "demon-king-auto", "Demon King Auto scale collectibles", "/static/assets/images/shop_models/Demon_King_Auto.png", 41),
    ("Diecast Masters", "diecast-masters", "Diecast Masters heavy equipment & scale models", "/static/assets/images/shop_models/Diecast_Masters.png", 42),
    ("FG Model", "fg-model", "FG Model scale collectibles", "/static/assets/images/shop_models/FG_Model.png", 43),
    ("GCD", "gcd", "GCD detailed 1:64 scale models", "/static/assets/images/shop_models/GCD_Diecast.png", 44),
    ("GDO", "gdo", "GDO scale collectibles", "/static/assets/images/shop_models/GDO.png", 45),
    ("GFCC", "gfcc", "GFCC classic diecast scale models", "/static/assets/images/shop_models/GFCC.png", 46),
    ("Ghost Player", "ghost-player", "Ghost Player scale collectibles", "/static/assets/images/shop_models/Ghost_Player.png", 47),
    ("GOC", "goc", "GOC scale collectibles", "/static/assets/images/shop_models/GOC_India.png", 48),
    ("GreenLight", "greenlight", "GreenLight Hollywood & Collector diecast models", "/static/assets/images/shop_models/Green_Light_Cars.png", 49),
    ("GTMAX", "gtmax", "GTMAX scale collectibles", "/static/assets/images/shop_models/GTMAX.png", 50),
    ("HG Model", "hg-model", "HG Model scale collectibles", "/static/assets/images/shop_models/HG_Model.png", 51),
    ("HKM Premium", "hkm-premium", "HKM Premium 1:64 scale collectibles", "/static/assets/images/shop_models/HKM_Premium.png", 52),
    ("Hobby Japan", "hobby-japan", "Hobby Japan precision JDM 1:64 collectibles", "/static/assets/images/shop_models/Hobby_Japan.png", 53),
    ("iHCM64", "ihcm64", "iHCM64 scale collectibles", "/static/assets/images/shop_models/iHCM64.png", 54),
    ("Jicar", "jicar", "Jicar scale collectibles", "/static/assets/images/shop_models/Jicar.png", 55),
    ("JiYi Model", "jiyi-model", "JiYi Model scale collectibles", "/static/assets/images/shop_models/JiYi_model.png", 56),
    ("Joy Junction", "joy-junction", "Joy Junction scale collectibles", "/static/assets/images/shop_models/Joy_Junction.png", 57),
    ("Kilo Works", "kilo-works", "Kilo Works high-detail diecast models", "/static/assets/images/shop_models/Kilo_Works.png", 58),
    ("Kinsmart", "kinsmart", "Kinsmart pull-back licensed diecast cars", "/static/assets/images/shop_models/Kinsmart_Diecast_Cars.png", 59),
    ("Massdi", "massdi", "Massdi licensed diecast scale models", "/static/assets/images/shop_models/Massdi_Diecast.png", 60),
    ("Micro Turbo", "micro-turbo", "Micro Turbo JDM & custom 1:64 models", "/static/assets/images/shop_models/Micro_Turbo.png", 61),
    ("MK Miniatures", "mk-miniatures", "MK Miniatures scale collectibles", "/static/assets/images/shop_models/MK_Miniatures.png", 62),
    ("Model Model", "model-model", "Model Model scale collectibles", "/static/assets/images/shop_models/Model_Model.png", 63),
    ("More Art", "more-art", "More Art collector dioramas & figurines", "/static/assets/images/shop_models/More_Art.png", 64),
    ("Motor Helix", "motor-helix", "Motor Helix opening-panel scale collectibles", "/static/assets/images/shop_models/Motor_Helix.png", 65),
    ("MSZ", "msz", "MSZ licensed scale diecast cars", "/static/assets/images/shop_models/MSZ.png", 66),
    ("My Model Collect", "my-model-collect", "My Model Collect scale collectibles", "/static/assets/images/shop_models/My_Model_Collect.png", 67),
    ("Nitro Blaze", "nitro-blaze", "Nitro Blaze scale collectibles", "/static/assets/images/shop_models/Nitro_Blaze.png", 68),
    ("NZG", "nzg", "NZG collector transport & commercial scale models", "/static/assets/images/shop_models/NZG.png", 69),
    ("Original Model", "original-model", "Original Model scale collectibles", "/static/assets/images/shop_models/Original_Model.png", 70),
    ("Para64", "para64", "Para64 licensed 1:64 diecast cars", "/static/assets/images/shop_models/Para_64_Diecast.png", 71),
    ("Perka", "perka", "Perka scale collectibles", "/static/assets/images/shop_models/Perka.png", 72),
    ("PosterCars", "postercars", "PosterCars Hypercar Collection 1:64 models", "/static/assets/images/shop_models/Poster_Cars_Diecast.png", 73),
    ("Rastar", "rastar", "Rastar licensed scale models", "/static/assets/images/shop_models/Rastar.png", 74),
    ("Rhino Model", "rhino-model", "Rhino Model 1:64 scale collectibles", "/static/assets/images/shop_models/RHINO_MODEL.png", 75),
    ("RMZ City", "rmz-city", "RMZ City diecast scale vehicles", "/static/assets/images/shop_models/RMZ_Diecast.png", 76),
    ("Shadow", "shadow", "Shadow scale collectibles", "/static/assets/images/shop_models/Shadow_Cars.png", 77),
    ("Shadow Pro", "shadow-pro", "Shadow Pro scale collectibles", "/static/assets/images/shop_models/Shadow_Pro.png", 78),
    ("SHOOM64", "shoom64", "SHOOM64 scale collectibles", "/static/assets/images/shop_models/SHOOM64.png", 79),
    ("Stance Hunters", "stance-hunters", "Stance Hunters widebody & tuner 1:64 models", "/static/assets/images/shop_models/Stance_Hunters.png", 80),
    ("Star Race", "star-race", "Star Race motorsport scale collectibles", "/static/assets/images/shop_models/STAR_RACE.png", 81),
    ("Supcar", "supcar", "Supcar scale collectibles", "/static/assets/images/shop_models/SUPCAR.png", 82),
    ("Takara Tomy", "takara-tomy", "Takara Tomy Tomica & Premium diecast cars", "/static/assets/images/shop_models/Takara_Tomy_India.png", 83),
    ("The Art of Model", "the-art-of-model", "The Art of Model collector editions", "/static/assets/images/shop_models/The_Art_of_Model.png", 84),
    ("TINY", "tiny", "TINY Hong Kong & JDM 1:64 scale models", "/static/assets/images/shop_models/TINY_Cars.png", 85),
    ("Trends Hobby", "trends-hobby", "Trends Hobby scale collectibles", "/static/assets/images/shop_models/Trends_Hobby.png", 86),
    ("Welly", "welly", "Welly NEX licensed scale diecast cars", "/static/assets/images/shop_models/Welly_Cars.png", 87),
    ("Whel Art", "whel-art", "Whel Art bespoke 1:64 collectibles", "/static/assets/images/shop_models/Whel_Art.png", 88),
    ("Works Model", "works-model", "Works Model scale collectibles", "/static/assets/images/shop_models/Works_Model.png", 89),
    ("XCarToys", "xcartoys", "XCarToys Pop Race & specialty 1:64 models", "/static/assets/images/shop_models/X_Car_Toys.png", 90),
    ("YS Model", "ys-model", "YS Model scale collectibles", "/static/assets/images/shop_models/YS_Model.png", 91),
    ("ZD Toys", "zd-toys", "ZD Toys licensed collector figures & vehicles", "/static/assets/images/shop_models/ZD_Toys.png", 92),
]

CATEGORIES = [
    ("1:64 Scale Models", "1-64-scale-models", "Precision 1:64 diecast cars & trucks", 1),
    ("1:43 Scale Models", "1-43-scale-models", "1:43 licensed supercars & GT models", 2),
    ("1:18 Centerpiece Models", "1-18-centerpiece-models", "Large 1:18 showcase collector models", 3),
    ("Limited & RLC Drops", "limited-rlc-drops", "Limited edition & Red Line Club allocations", 4),
    ("Pre-Order Drops", "pre-order-drops", "Upcoming international releases open for token booking", 5),
    ("Dioramas & Supplies", "dioramas-supplies", "LED garage dioramas & card protectors", 6),
    ("Events Exclusive", "events-exclusive", "Convention, show & special collector event exclusive releases", 7),
]

PRODUCTS_SEED = [
    {
        "sku": "DWI-001",
        "name": "Mini GT #522 - Nissan Skyline GT-R (R34) V-Spec II N1 White",
        "brand": "Mini GT",
        "category": "1:64 Scale Models",
        "manufacturer": "TSM Model",
        "vehicle_model": "Nissan Skyline GT-R (R34) V-Spec II N1",
        "scale": "1:64",
        "price_inr": 1499,
        "mrp_inr": 1699,
        "availability_status": "in_stock",
        "badge_text": "Bestseller",
        "badge_type": "stock-in",
        "is_featured": 1,
        "is_limited_edition": 0,
        "is_pre_order": 0,
        "garage_hold_eligible": 1,
        "stock_qty": 8,
        "image": "https://images.unsplash.com/photo-1617788138017-80ad40651399?auto=format&fit=crop&w=700&q=80",
        "description": "Iconic N1 homologation spec of the Godzilla R34. Featuring razor-sharp front aero, factory white racing finish, gold Brembo calipers, and authentic twin-turbo badge details.",
        "specs": {
            "chassis": "Diecast Metal",
            "wheels": "Real Rider Rubber",
            "opening": "Fixed (Precision Sealed)",
            "packaging": "Sealed Blister Card + Protector",
        },
        "tags": "jdm,nissan,skyline,r34,minigt,bestseller",
    },
    {
        "sku": "DWI-002",
        "name": "Kaido House x Mini GT #075 - Datsun 510 Pro Street OG Orange",
        "brand": "Kaido House",
        "category": "Limited & RLC Drops",
        "manufacturer": "Kaido House / Mini GT",
        "vehicle_model": "Datsun 510 Pro Street",
        "scale": "1:64",
        "price_inr": 2399,
        "mrp_inr": 2699,
        "availability_status": "hot_drop",
        "badge_text": "Opening Hood",
        "badge_type": "hot-drop",
        "is_featured": 1,
        "is_limited_edition": 1,
        "is_pre_order": 0,
        "garage_hold_eligible": 1,
        "stock_qty": 3,
        "image": "https://images.unsplash.com/photo-1552519507-da3b142c6e3d?auto=format&fit=crop&w=700&q=80",
        "description": "Designed by Jun Imai. Showcases a custom twin-carb inline engine bay, wide flared fenders, rolled roll cage, and stunning multi-stage metallic burnt orange livery.",
        "specs": {
            "chassis": "Diecast Metal Base & Body",
            "wheels": "Alloy Chrome Rim + Rubber",
            "opening": "Full Opening Hood & Detailed Engine",
            "packaging": "Collector Magnetic Flip-Top Box",
        },
        "tags": "kaido,datsun,510,jun imai,opening hood,hot drop",
    },
    {
        "sku": "DWI-003",
        "name": "Pop Race - Pandem Toyota GR Yaris Advan Livery",
        "brand": "Pop Race",
        "category": "1:64 Scale Models",
        "manufacturer": "Pop Race",
        "vehicle_model": "Pandem Toyota GR Yaris",
        "scale": "1:64",
        "price_inr": 1899,
        "mrp_inr": 2099,
        "availability_status": "in_stock",
        "badge_text": "Full Openings",
        "badge_type": "stock-in",
        "is_featured": 1,
        "is_limited_edition": 0,
        "is_pre_order": 0,
        "garage_hold_eligible": 1,
        "stock_qty": 5,
        "image": "https://images.unsplash.com/photo-1503376780353-7e6692767b70?auto=format&fit=crop&w=700&q=80",
        "description": "The hottest rally pocket-rocket fitted with Pandem widebody kit and iconic red-black Advan racing livery. Both hood and rear hatch open smoothly.",
        "specs": {
            "chassis": "Diecast Zinc Alloy",
            "wheels": "Yokohama Advan Slicks",
            "opening": "Opening Engine Hood & Rear Hatch",
            "packaging": "Clear Acrylic Display Case with Base",
        },
        "tags": "poprace,toyota,yaris,advan,pandem,rally",
    },
    {
        "sku": "DWI-004",
        "name": "Inno64 - Honda Civic Ferio EG9 #15 Idemitsu Motion MAC Tools",
        "brand": "Inno64",
        "category": "1:64 Scale Models",
        "manufacturer": "Inno Models",
        "vehicle_model": "Honda Civic Ferio EG9 #15",
        "scale": "1:64",
        "price_inr": 1999,
        "mrp_inr": 2299,
        "availability_status": "in_stock",
        "badge_text": "Acrylic Case",
        "badge_type": "chase-tag",
        "is_featured": 1,
        "is_limited_edition": 0,
        "is_pre_order": 0,
        "garage_hold_eligible": 1,
        "stock_qty": 4,
        "image": "https://images.unsplash.com/photo-1542282088-72c9c27ed0cd?auto=format&fit=crop&w=700&q=80",
        "description": "Famous JTCC circuit racer. Includes extra set of custom gold racing wheels, replacement decals, and velvet base presentation.",
        "specs": {
            "chassis": "Diecast High Detail",
            "wheels": "Racing Slicks with Decals",
            "opening": "Fixed Body / Detailed Roll Cage",
            "packaging": "Premium Acrylic Display Case with Custom Screwed Plaque",
        },
        "tags": "inno64,honda,civic,eg9,idemitsu,jtcc",
    },
    {
        "sku": "DWI-005",
        "name": "Hot Wheels RLC Exclusive - 1993 Ford Mustang Cobra R",
        "brand": "Hot Wheels",
        "category": "Limited & RLC Drops",
        "manufacturer": "Mattel Hot Wheels",
        "vehicle_model": "1993 Ford Mustang Cobra R",
        "scale": "1:64",
        "price_inr": 3499,
        "mrp_inr": 3999,
        "availability_status": "hot_drop",
        "badge_text": "RLC Limited Drop",
        "badge_type": "hot-drop",
        "is_featured": 1,
        "is_limited_edition": 1,
        "is_pre_order": 0,
        "garage_hold_eligible": 1,
        "stock_qty": 2,
        "image": "https://images.unsplash.com/photo-1584345604476-8ec5e12e42dd?auto=format&fit=crop&w=700&q=80",
        "description": "Red Line Club official release in mirror-like Spectraflame Vibrant Red. Limited allocation strictly restricted to 1 unit per collector.",
        "specs": {
            "chassis": "Full Metal/Metal",
            "wheels": "Real Riders 5-Spoke Chrome",
            "opening": "Opening Hood with 5.0L Engine",
            "packaging": "Kar Keepers Clamshell + Numbered Holo Seal",
        },
        "tags": "hotwheels,rlc,mustang,cobra,spectraflame,limited",
    },
    {
        "sku": "DWI-006",
        "name": "Tarmac Works - Porsche 911 GT3 R #911 Manthey Racing Grello",
        "brand": "Tarmac Works",
        "category": "1:64 Scale Models",
        "manufacturer": "Tarmac Works",
        "vehicle_model": "Porsche 911 GT3 R #911 Manthey",
        "scale": "1:64",
        "price_inr": 1799,
        "mrp_inr": 1999,
        "availability_status": "in_stock",
        "badge_text": "Nurburgring Hero",
        "badge_type": "stock-in",
        "is_featured": 1,
        "is_limited_edition": 0,
        "is_pre_order": 0,
        "garage_hold_eligible": 1,
        "stock_qty": 6,
        "image": "https://images.unsplash.com/photo-1614162692292-7ac56d7f7f1e?auto=format&fit=crop&w=700&q=80",
        "description": "The fan-favorite 'Grello' high-downforce Porsche 911 GT3 R that conquered the 24 Hours of Nurburgring. Features flawless neon yellow & green livery print.",
        "specs": {
            "chassis": "Diecast Metal",
            "wheels": "BBS Racing Monoblock",
            "opening": "Sealed Motorsport Casting",
            "packaging": "Window Box + Collector Card",
        },
        "tags": "tarmac,porsche,911,gt3r,manthey,grello,nurburgring",
    },
    {
        "sku": "DWI-007",
        "name": "Mini GT #612 - Pagani Utopia Bianco Rinascimento",
        "brand": "Mini GT",
        "category": "1:64 Scale Models",
        "manufacturer": "TSM Model",
        "vehicle_model": "Pagani Utopia",
        "scale": "1:64",
        "price_inr": 1549,
        "mrp_inr": 1749,
        "availability_status": "in_stock",
        "badge_text": "Hypercar",
        "badge_type": "stock-in",
        "is_featured": 0,
        "is_limited_edition": 0,
        "is_pre_order": 0,
        "garage_hold_eligible": 1,
        "stock_qty": 7,
        "image": "https://images.unsplash.com/photo-1544829099-b9a0c07fad1a?auto=format&fit=crop&w=700&q=80",
        "description": "Horacio Pagani's twin-turbo V12 masterpiece recreated with photorealistic quad-exhaust tips, interior gated shifter visibility, and fine etched wing mirrors.",
        "specs": {
            "chassis": "Diecast Chassis & Body",
            "wheels": "Turbine Style Wheels + Rubber",
            "opening": "Sealed Precision Mold",
            "packaging": "Sealed Blister Box",
        },
        "tags": "minigt,pagani,utopia,hypercar",
    },
    {
        "sku": "DWI-008",
        "name": "Almost Real - Land Rover Defender 90 Camel Trophy 1989",
        "brand": "Almost Real",
        "category": "1:64 Scale Models",
        "manufacturer": "Almost Real",
        "vehicle_model": "Land Rover Defender 90 Camel Trophy",
        "scale": "1:64",
        "price_inr": 2199,
        "mrp_inr": 2499,
        "availability_status": "in_stock",
        "badge_text": "Official Dealer",
        "badge_type": "chase-tag",
        "is_featured": 0,
        "is_limited_edition": 0,
        "is_pre_order": 0,
        "garage_hold_eligible": 1,
        "stock_qty": 4,
        "image": "https://images.unsplash.com/photo-1519641471654-76ce0107ad1b?auto=format&fit=crop&w=700&q=80",
        "description": "Diecast World India is an authorized showcase for Almost Real. Featuring authentic sand-glow paint, rooftop luggage rack, jerry cans, and recovery ladder accessories.",
        "specs": {
            "chassis": "Diecast Heavyweight",
            "wheels": "Deep Tread Offroad Rubber",
            "opening": "Working Suspensions",
            "packaging": "Acrylic Display Case with Sand Base",
        },
        "tags": "almost real,defender,land rover,camel trophy",
    },
    {
        "sku": "DWI-009",
        "name": "Bburago Signature - Ferrari 296 GTB Rosso Corsa (1:43)",
        "brand": "Bburago",
        "category": "1:43 Scale Models",
        "manufacturer": "Bburago",
        "vehicle_model": "Ferrari 296 GTB",
        "scale": "1:43",
        "price_inr": 1299,
        "mrp_inr": 1499,
        "availability_status": "in_stock",
        "badge_text": "1:43 Scale",
        "badge_type": "stock-in",
        "is_featured": 0,
        "is_limited_edition": 0,
        "is_pre_order": 0,
        "garage_hold_eligible": 1,
        "stock_qty": 5,
        "image": "https://images.unsplash.com/photo-1592198084033-aade902d1aae?auto=format&fit=crop&w=700&q=80",
        "description": "Official Ferrari licensed 1:43 scale model. Ferrari shield tampo prints on front fenders, silver brake calipers, and authentic cockpit instrumentation.",
        "specs": {
            "chassis": "Diecast Metal",
            "wheels": "Pirelli P-Zero Tread Rubber",
            "opening": "Detailed Engine Cover Window",
            "packaging": "Signature Hard Acrylic Case",
        },
        "tags": "bburago,ferrari,296,gtb,1:43",
    },
    {
        "sku": "DWI-010",
        "name": "Solido - Nissan GT-R R35 Liberty Walk Metallic Blue (1:18)",
        "brand": "Solido",
        "category": "1:18 Centerpiece Models",
        "manufacturer": "Solido",
        "vehicle_model": "Nissan GT-R R35 Liberty Walk",
        "scale": "1:18",
        "price_inr": 5999,
        "mrp_inr": 6699,
        "availability_status": "in_stock",
        "badge_text": "1:18 Showcase",
        "badge_type": "hot-drop",
        "is_featured": 1,
        "is_limited_edition": 0,
        "is_pre_order": 0,
        "garage_hold_eligible": 1,
        "stock_qty": 3,
        "image": "https://images.unsplash.com/photo-1502877338535-766e1452684a?auto=format&fit=crop&w=700&q=80",
        "description": "Centerpiece 1:18 scale model for your collector garage. Features LB Works flared arches, massive carbon-look GT wing, roll cage, and functional steering mechanism.",
        "specs": {
            "chassis": "Diecast Metal Body",
            "wheels": "Posable Steerable Front Wheels",
            "opening": "Opening Doors with Full Interior",
            "packaging": "Large Window Collector Box",
        },
        "tags": "solido,nissan,gtr,r35,liberty walk,1:18",
    },
    {
        "sku": "DWI-011",
        "name": "Kaido House x Mini GT #089 - Chevy Silverado Dually Kaido Works",
        "brand": "Kaido House",
        "category": "Pre-Order Drops",
        "manufacturer": "Kaido House / Mini GT",
        "vehicle_model": "Chevy Silverado Dually Kaido Works",
        "scale": "1:64",
        "price_inr": 2599,
        "mrp_inr": 2899,
        "availability_status": "pre_order",
        "badge_text": "Pre-Order Jan '27",
        "badge_type": "pre-order",
        "is_featured": 0,
        "is_limited_edition": 1,
        "is_pre_order": 1,
        "garage_hold_eligible": 1,
        "stock_qty": 10,
        "expected_release_date": "2027-01-10",
        "expected_arrival_date": "Late January 2027",
        "pre_order_token_inr": 499,
        "pre_order_allocation": 10,
        "pre_order_limit": 2,
        "pre_order_closing_date": "2027-01-05",
        "image": "https://images.unsplash.com/photo-1533473359331-0135ef1b58bf?auto=format&fit=crop&w=700&q=80",
        "description": "Upcoming international drop. Extreme slammed stance dually truck with custom Kaido Works bed rack. Lock yours with a token advance of ₹499.",
        "specs": {
            "chassis": "Diecast Metal Slammed Base",
            "wheels": "Dually 6-Wheel Custom Setup",
            "opening": "Opening Hood + Drop Tailgate",
            "packaging": "Kaido House Magnetic Sealed Box",
        },
        "tags": "kaido,silverado,dually,preorder",
    },
    {
        "sku": "DWI-012",
        "name": "Pop Race - Singer DLS Metallic Forest Green / Tan Interior",
        "brand": "Pop Race",
        "category": "Pre-Order Drops",
        "manufacturer": "Pop Race",
        "vehicle_model": "Porsche 911 Singer DLS",
        "scale": "1:64",
        "price_inr": 1849,
        "mrp_inr": 2099,
        "availability_status": "pre_order",
        "badge_text": "Pre-Order Feb '27",
        "badge_type": "pre-order",
        "is_featured": 0,
        "is_limited_edition": 1,
        "is_pre_order": 1,
        "garage_hold_eligible": 1,
        "stock_qty": 12,
        "expected_release_date": "2027-02-01",
        "expected_arrival_date": "Mid February 2027",
        "pre_order_token_inr": 399,
        "pre_order_allocation": 12,
        "pre_order_limit": 2,
        "pre_order_closing_date": "2027-01-25",
        "image": "https://images.unsplash.com/photo-1503376780353-7e6692767b70?auto=format&fit=crop&w=700&q=80",
        "description": "Reimagined 911 air-cooled beauty. Full carbon fiber weave textures on roof and wing, delicate leather interior detailing. Reserve now with ₹399 token.",
        "specs": {
            "chassis": "Diecast Metal",
            "wheels": "Fuchs Inspired Alloy Wheels",
            "opening": "Opening Rear Engine Bay & Front Hood",
            "packaging": "Acrylic Display Case",
        },
        "tags": "poprace,singer,porsche,911,preorder",
    },
    {
        "sku": "DWI-013",
        "name": "Morepost - Japanese Underground RWB Parking Garage with LED Lights",
        "brand": "Accessories",
        "category": "Dioramas & Supplies",
        "manufacturer": "Morepost",
        "vehicle_model": "Underground RWB Parking Garage",
        "scale": "Accessories",
        "price_inr": 2799,
        "mrp_inr": 3299,
        "availability_status": "in_stock",
        "badge_text": "Diorama LED",
        "badge_type": "chase-tag",
        "is_featured": 0,
        "is_limited_edition": 0,
        "is_pre_order": 0,
        "garage_hold_eligible": 1,
        "stock_qty": 5,
        "image": "https://images.unsplash.com/photo-1506521781263-d8422e82f27a?auto=format&fit=crop&w=700&q=80",
        "description": "Turn your diecast cars into a photogenic Tokyo garage. Features weathered concrete textures, graffiti wall decals, warning stripes, and bright overhead LED lighting.",
        "specs": {
            "chassis": "High Density Acrylic + PVC",
            "wheels": "Fits 6-8 1:64 Scale Cars",
            "opening": "USB Powered Ceiling LED Lights",
            "packaging": "Protective Flatpack with Guide",
        },
        "tags": "diorama,led,garage,rwb,accessories",
    },
    {
        "sku": "DWI-014",
        "name": "Diecast World India - 5-Layer Blister Card Protectors (Pack of 10)",
        "brand": "Accessories",
        "category": "Dioramas & Supplies",
        "manufacturer": "Diecast World India",
        "vehicle_model": "5-Layer Blister Card Protectors",
        "scale": "Accessories",
        "price_inr": 499,
        "mrp_inr": 650,
        "availability_status": "in_stock",
        "badge_text": "Mint Armor",
        "badge_type": "stock-in",
        "is_featured": 0,
        "is_limited_edition": 0,
        "is_pre_order": 0,
        "garage_hold_eligible": 1,
        "stock_qty": 25,
        "image": "https://images.unsplash.com/photo-1558981403-c5f9899a28bc?auto=format&fit=crop&w=700&q=80",
        "description": "Protect your expensive Hot Wheels Premiums, Car Culture, and Mini GT blister cards from corner dog-ears, soft edges, and dust.",
        "specs": {
            "chassis": "Ultra-Clear Acid-Free 0.5mm PET",
            "wheels": "UV Resistant Coating",
            "opening": "Snug Fit Clamshell with Hanging Tab",
            "packaging": "Pack of 10 Pieces",
        },
        "tags": "protector,blister,accessories,armor",
    },
]

SHOWCASE_SLIDES = [
    ("Ferrari 499P Hypercar", "https://images.unsplash.com/photo-1568605117036-5fe5e7bab0b7?auto=format&fit=max&w=1920&q=85"),
    ("Porsche 911 GT3 R Manthey Grello", "https://images.unsplash.com/photo-1614162692292-7ac56d7f7f1e?auto=format&fit=max&w=1920&q=85"),
    ("Nissan Skyline GT-R R34", "https://images.unsplash.com/photo-1617788138017-80ad40651399?auto=format&fit=max&w=1920&q=85"),
    ("McLaren 720S GT3", "https://images.unsplash.com/photo-1621135802920-133df287f89c?auto=format&fit=max&w=1920&q=85"),
    ("Lamborghini Huracan Super Trofeo", "https://images.unsplash.com/photo-1544829099-b9a0c07fad1a?auto=format&fit=max&w=1920&q=85"),
    ("Audi R8 LMS GT3", "https://images.unsplash.com/photo-1603584173870-7f23fdae1b7a?auto=format&fit=max&w=1920&q=85"),
    ("BMW M4 GT3", "https://images.unsplash.com/photo-1555215695-3004980ad54e?auto=format&fit=max&w=1920&q=85"),
    ("Mercedes-AMG GT3", "https://images.unsplash.com/photo-1618843479313-40f8afb4b4d8?auto=format&fit=max&w=1920&q=85"),
    ("Toyota GR Supra GT4", "https://images.unsplash.com/photo-1580273916550-e323be2ae537?auto=format&fit=max&w=1920&q=85"),
    ("Aston Martin Vantage GTE", "https://images.unsplash.com/photo-1503376780353-7e6692767b70?auto=format&fit=max&w=1920&q=85"),
]

HERO_SLIDES = [
    {
        "sku": "DWI-001",
        "badge_text": "JDM MOTORSPORT LEGEND",
        "badge_style": "",
        "title": "Mini GT #522 Nissan Skyline GT-R (R34) V-Spec II N1",
        "subtitle": "Pure Homologation White • Nürburgring 24h & Super Taikyu DNA",
        "image_url": "https://images.unsplash.com/photo-1617788138017-80ad40651399?auto=format&fit=max&w=1000&q=80",
        "meta": {
            "grail_tag": "GODZILLA RACING #522",
            "chips": ["Real Rider Slicks", "Diecast Heavy Base", "Factory N1 Aero", "Sealed Blister + Protector"],
        },
    },
    {
        "sku": "DWI-006",
        "badge_text": "24H NÜRBURGRING WINNER",
        "badge_style": "background: linear-gradient(135deg, #84cc16, #22c55e); color: #000;",
        "title": "Tarmac Works - Porsche 911 GT3 R Manthey 'Grello' #911",
        "subtitle": "Iconic Neon Green-Yellow Livery • Green Hell King",
        "image_url": "https://images.unsplash.com/photo-1614162692292-7ac56d7f7f1e?auto=format&fit=max&w=1000&q=80",
        "meta": {
            "grail_tag": "NÜRBURGRING HERO",
            "chips": ["BBS Monoblock Slicks", "High-Downforce GT Wing", "Manthey Licensed", "Window Box + Collector Card"],
        },
    },
    {
        "sku": "DWI-002",
        "badge_text": "JUN IMAI CUSTOM PRO STREET",
        "badge_style": "background: linear-gradient(135deg, #f97316, #ea580c); color: #fff;",
        "title": "Kaido House x Mini GT #075 Datsun 510 Pro Street",
        "subtitle": "Full Opening Hood with Detailed Twin-Carb Engine Bay",
        "image_url": "https://images.unsplash.com/photo-1552519507-da3b142c6e3d?auto=format&fit=max&w=1000&q=80",
        "meta": {
            "grail_tag": "KAIDO WORKS OG",
            "chips": ["Opening Engine Hood", "Alloy Chrome Deep Rim", "Diecast Metal Chassis", "Magnetic Flip-Top Box"],
        },
    },
    {
        "sku": "DWI-003",
        "badge_text": "WRC RALLY MONSTER",
        "badge_style": "background: linear-gradient(135deg, #ef4444, #b91c1c); color: #fff;",
        "title": "Pop Race - Pandem Toyota GR Yaris Advan Racing",
        "subtitle": "Rocket Bunny Widebody • Opening Engine Hood & Rear Hatch",
        "image_url": "https://images.unsplash.com/photo-1503376780353-7e6692767b70?auto=format&fit=max&w=1000&q=80",
        "meta": {
            "grail_tag": "ADVAN RACING SPEC",
            "chips": ["Dual Hood & Hatch", "Yokohama Advan Slicks", "Zinc Alloy Diecast", "Acrylic Case + Base"],
        },
    },
    {
        "sku": "DWI-004",
        "badge_text": "JTCC TOURING CAR CHAMPION",
        "badge_style": "background: linear-gradient(135deg, #3b82f6, #1d4ed8); color: #fff;",
        "title": "Inno64 - Honda Civic Ferio EG9 #15 Idemitsu MAC Tools",
        "subtitle": "Circuit Legend • Includes Extra Set of Gold Racing Wheels",
        "image_url": "https://images.unsplash.com/photo-1542282088-72c9c27ed0cd?auto=format&fit=max&w=1000&q=80",
        "meta": {
            "grail_tag": "JTCC SUZUKA WINNER",
            "chips": ["Dual Wheel Sets Included", "Screwed Metal Plaque", "Full Interior Roll Cage", "Collector Display Box"],
        },
    },
    {
        "sku": "DWI-005",
        "badge_text": "RED LINE CLUB COLLECTOR GRAIL",
        "badge_style": "background: linear-gradient(135deg, #dc2626, #7f1d1d); color: #fff;",
        "title": "Hot Wheels RLC Exclusive - 1993 Ford Mustang Cobra R",
        "subtitle": "Mirror Spectraflame Vibrant Red • Opening 5.0L Engine Hood",
        "image_url": "https://images.unsplash.com/photo-1584345604476-8ec5e12e42dd?auto=format&fit=max&w=1000&q=80",
        "meta": {
            "grail_tag": "RLC LIMITED DROP",
            "chips": ["Opening Hood with 5.0L", "Real Riders 5-Spoke Chrome", "Full Metal/Metal Body", "Kar Keepers Clamshell"],
        },
    },
]

INSTAGRAM_POSTS = [
    ("DWI-001", "Mini GT R34 V-Spec II N1 Homologation", "https://images.unsplash.com/photo-1617788138017-80ad40651399?auto=format&fit=max&w=500&q=80"),
    ("DWI-002", "Kaido House Jun Imai Pro Street 510", "https://images.unsplash.com/photo-1552519507-da3b142c6e3d?auto=format&fit=max&w=500&q=80"),
    ("DWI-003", "Pop Race GR Yaris Advan Livery", "https://images.unsplash.com/photo-1503376780353-7e6692767b70?auto=format&fit=max&w=500&q=80"),
    ("DWI-004", "Inno64 Idemitsu Civic Ferio EG9 Suzuka", "https://images.unsplash.com/photo-1542282088-72c9c27ed0cd?auto=format&fit=max&w=500&q=80"),
    ("DWI-006", "Manthey Racing 911 GT3 R Grello", "https://images.unsplash.com/photo-1614162692292-7ac56d7f7f1e?auto=format&fit=max&w=500&q=80"),
    ("DWI-013", "Tokyo Underground LED Diorama Hub", "https://images.unsplash.com/photo-1506521781263-d8422e82f27a?auto=format&fit=max&w=500&q=80"),
]


def init_and_seed_database(
    db_path: str,
    migrations_dir: str,
    admin_username: str = "admin",
    admin_email: str = "diecastworldindia@gmail.com",
    admin_full_name: str = "Priyal Shah",
    admin_password: str = "ChangeMe@2026!",
    seed_demo_products: bool = True,
) -> None:
    """Initialize schema migrations and seed default store data idempotently."""
    run_migrations(db_path, migrations_dir)
    conn = open_connection(db_path)
    try:
        conn.execute("BEGIN IMMEDIATE;")

        # 1. Seed default Admin user if none exist
        admin_count = conn.execute("SELECT COUNT(*) FROM admin_users").fetchone()[0]
        if admin_count == 0:
            conn.execute(
                """
                INSERT INTO admin_users (username, email, full_name, password_hash, role, is_active)
                VALUES (?, ?, ?, ?, 'owner', 1)
                """,
                (
                    admin_username,
                    admin_email,
                    admin_full_name,
                    generate_password_hash(admin_password),
                ),
            )

        # 2. Seed Store Settings
        for key, value, val_type, desc in DEFAULT_SETTINGS:
            conn.execute(
                """
                INSERT OR IGNORE INTO store_settings (key, value, value_type, description)
                VALUES (?, ?, ?, ?)
                """,
                (key, value, val_type, desc),
            )

        # 3. Seed Brands
        for name, slug, desc, sort_order in BRANDS:
            conn.execute(
                """
                INSERT OR IGNORE INTO brands (name, slug, description, sort_order, is_featured, is_active)
                VALUES (?, ?, ?, ?, 1, 1)
                """,
                (name, slug, desc, sort_order),
            )
        for name, slug, desc, logo_path, sort_order in EXTRA_BRANDS:
            conn.execute(
                """
                INSERT OR IGNORE INTO brands (name, slug, description, logo_path, sort_order, is_featured, is_active)
                VALUES (?, ?, ?, ?, ?, 0, 1)
                """,
                (name, slug, desc, logo_path, sort_order),
            )

        # 4. Seed Categories
        for name, slug, desc, sort_order in CATEGORIES:
            conn.execute(
                """
                INSERT OR IGNORE INTO categories (name, slug, description, sort_order, is_active)
                VALUES (?, ?, ?, ?, 1)
                """,
                (name, slug, desc, sort_order),
            )

        # 5. Seed Demo Products only when explicitly enabled (e.g. test runs)
        product_count = conn.execute("SELECT COUNT(*) FROM products").fetchone()[0]
        if seed_demo_products and product_count == 0:
            brand_map = {
                r["name"]: r["id"]
                for r in conn.execute("SELECT id, name FROM brands").fetchall()
            }
            cat_map = {
                r["name"]: r["id"]
                for r in conn.execute("SELECT id, name FROM categories").fetchall()
            }

            for p in PRODUCTS_SEED:
                price_paise = p["price_inr"] * 100
                mrp_paise = p["mrp_inr"] * 100
                discount_pct = (
                    round(((mrp_paise - price_paise) / mrp_paise) * 100)
                    if mrp_paise > price_paise
                    else 0
                )
                token_paise = p.get("pre_order_token_inr", 0) * 100
                slug = f"{slugify(p['sku'])}-{slugify(p['name'])[:60]}"
                cur = conn.execute(
                    """
                    INSERT INTO products (
                        sku, slug, name, brand_id, category_id, manufacturer, vehicle_model,
                        scale, price_paise, mrp_paise, discount_percent, badge_text, badge_type,
                        description, specifications_json, availability_status, tags,
                        is_featured, is_limited_edition, is_sold_out, is_pre_order,
                        garage_hold_eligible, expected_release_date, expected_arrival_date,
                        pre_order_token_paise, pre_order_allocation, pre_order_reserved_count,
                        pre_order_limit_per_customer, pre_order_closing_date, is_visible
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, 0, ?, ?, 1)
                    """,
                    (
                        p["sku"],
                        slug,
                        p["name"],
                        brand_map[p["brand"]],
                        cat_map[p["category"]],
                        p["manufacturer"],
                        p["vehicle_model"],
                        p["scale"],
                        price_paise,
                        mrp_paise,
                        discount_pct,
                        p["badge_text"],
                        p["badge_type"],
                        p["description"],
                        json.dumps(p["specs"]),
                        p["availability_status"],
                        p["tags"],
                        p["is_featured"],
                        p["is_limited_edition"],
                        p["is_pre_order"],
                        p["garage_hold_eligible"],
                        p.get("expected_release_date", ""),
                        p.get("expected_arrival_date", ""),
                        token_paise,
                        p.get("pre_order_allocation", 0),
                        p.get("pre_order_limit", 2),
                        p.get("pre_order_closing_date", ""),
                    ),
                )
                product_id = cur.lastrowid
                conn.execute(
                    """
                    INSERT INTO product_images (product_id, image_url, is_primary, sort_order, alt_text)
                    VALUES (?, ?, 1, 0, ?)
                    """,
                    (product_id, p["image"], p["name"]),
                )
                conn.execute(
                    """
                    INSERT INTO inventory (product_id, stock_qty, reserved_qty, low_stock_threshold)
                    VALUES (?, ?, 0, 3)
                    """,
                    (product_id, p["stock_qty"]),
                )
                conn.execute(
                    """
                    INSERT INTO inventory_history (
                        product_id, change_qty, previous_qty, new_qty, change_type, note, actor_type
                    ) VALUES (?, ?, 0, ?, 'initial', 'Initial collector catalog stock', 'system')
                    """,
                    (product_id, p["stock_qty"], p["stock_qty"]),
                )

        # 6. Seed Homepage Sections if empty
        section_count = conn.execute("SELECT COUNT(*) FROM homepage_sections").fetchone()[0]
        if section_count == 0:
            for idx, (title, img_url) in enumerate(SHOWCASE_SLIDES):
                conn.execute(
                    """
                    INSERT INTO homepage_sections (section_type, title, image_url, sort_order, is_active)
                    VALUES ('showcase_slide', ?, ?, ?, 1)
                    """,
                    (title, img_url, idx),
                )
            if seed_demo_products:
                for idx, hs in enumerate(HERO_SLIDES):
                    conn.execute(
                        """
                        INSERT INTO homepage_sections (
                            section_type, title, subtitle, badge_text, badge_style,
                            image_url, link_product_sku, meta_json, sort_order, is_active
                        ) VALUES ('hero_slide', ?, ?, ?, ?, ?, ?, ?, ?, 1)
                        """,
                        (
                            hs["title"],
                            hs["subtitle"],
                            hs["badge_text"],
                            hs["badge_style"],
                            hs["image_url"],
                            hs["sku"],
                            json.dumps(hs["meta"]),
                            idx,
                        ),
                    )
                for idx, (sku, caption, img_url) in enumerate(INSTAGRAM_POSTS):
                    conn.execute(
                        """
                        INSERT INTO homepage_sections (
                            section_type, title, image_url, link_product_sku, sort_order, is_active
                        ) VALUES ('instagram_post', ?, ?, ?, ?, 1)
                        """,
                        (caption, img_url, sku, idx),
                    )

        # 7. Seed starter collector coupon if empty
        coupon_count = conn.execute("SELECT COUNT(*) FROM coupons").fetchone()[0]
        if coupon_count == 0:
            conn.execute(
                """
                INSERT INTO coupons (
                    code, description, discount_type, discount_value,
                    min_order_paise, max_discount_paise, usage_limit, per_customer_limit, is_active
                ) VALUES ('COLLECTOR10', '10% off orders above ₹1,500 (max ₹300)', 'percent', 10, 150000, 30000, 500, 2, 1)
                """
            )

        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()
