"""
Seed script for maintenance module.
Populates: MaintenanceAsset (all machines from Excel) and MaintenanceChecklistItem (from PM checklist Excel).
Run from backend/ directory: python scripts/seed_maintenance.py
"""
import asyncio
import uuid
import os
import sys
from datetime import datetime, timezone

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

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.future import select
from dotenv import load_dotenv

load_dotenv()
DATABASE_URL = os.environ.get("DATABASE_URL")
if not DATABASE_URL:
    raise RuntimeError("DATABASE_URL is not set. Check your .env file.")
engine = create_async_engine(DATABASE_URL)
Session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

from app.models.maintenance_models import MaintenanceAsset, MaintenanceChecklistItem

# ─── ASSETS FROM EXCEL HISTORY CARDS ─────────────────────────────────────────
ASSETS = [
    # CO2 MIG Machines (42 machines)
    *[{"name": "CO2 MIG", "machine_number": i, "machine_type": "CO2_MIG", "year_of_commissioning": 2026} for i in range(1, 43)],
    # Blowers (8 machines)
    *[{"name": "Blower", "machine_number": i, "machine_type": "BLOWER", "year_of_commissioning": 2026} for i in range(1, 9)],
    # Compressors (3 machines)
    *[{"name": "Compressor", "machine_number": i, "machine_type": "COMPRESSOR", "year_of_commissioning": 2026} for i in range(1, 4)],
    # Hoists (10 machines)
    *[{"name": "Hoist", "machine_number": i, "machine_type": "HOIST", "year_of_commissioning": 2026} for i in range(1, 11)],
    # Ovan (1 machine)
    {"name": "Ovan", "machine_number": 1, "machine_type": "OVAN", "year_of_commissioning": 2026},
    # Shower (1 machine)
    {"name": "Shower", "machine_number": 1, "machine_type": "SHOWER", "year_of_commissioning": 2023},
    # Other types from PM checklist
    {"name": "DG Set", "machine_number": 1, "machine_type": "DG_SET", "year_of_commissioning": 2026},
    {"name": "Voltage Stabilizer", "machine_number": 1, "machine_type": "VOLTAGE_STABILIZER", "year_of_commissioning": 2026},
    {"name": "Control Panel", "machine_number": 1, "machine_type": "CONTROL_PANEL", "year_of_commissioning": 2026},
    {"name": "Arc Machine", "machine_number": 1, "machine_type": "ARC_MACHINE", "year_of_commissioning": 2026},
    {"name": "Plasma Cutter", "machine_number": 1, "machine_type": "PLASMA_CUTTER", "year_of_commissioning": 2026},
    {"name": "IR Lamp", "machine_number": 1, "machine_type": "IR_LAMP", "year_of_commissioning": 2026},
    {"name": "Dryer", "machine_number": 1, "machine_type": "DRYER", "year_of_commissioning": 2026},
    {"name": "Shearing M/C", "machine_number": 1, "machine_type": "SHEARING_MACHINE", "year_of_commissioning": 2026},
    {"name": "Disc Cutter", "machine_number": 1, "machine_type": "DISC_CUTTER", "year_of_commissioning": 2026},
    {"name": "Electric Grinder", "machine_number": 1, "machine_type": "ELECTRIC_GRINDER", "year_of_commissioning": 2026},
    {"name": "CO2 Gas Plant", "machine_number": 1, "machine_type": "CO2_GAS_PLANT", "year_of_commissioning": 2026},
    {"name": "Vacuum Cleaner", "machine_number": 1, "machine_type": "VACUUM_CLEANER", "year_of_commissioning": 2026},
]

# ─── PM CHECKLIST ITEMS (from 07Preventive Maint. Check Point.xls) ───────────
CHECKLIST = [
    # CO2 MIG
    {"machine_type": "CO2_MIG", "sr_no": 1, "check_point": "Check primary voltage fluctuation"},
    {"machine_type": "CO2_MIG", "sr_no": 2, "check_point": "Check the torch cable, switch, handle, servo motor"},
    {"machine_type": "CO2_MIG", "sr_no": 3, "check_point": "Check the gas flow and leakage"},
    {"machine_type": "CO2_MIG", "sr_no": 4, "check_point": "Check torch cables ok or not"},
    {"machine_type": "CO2_MIG", "sr_no": 5, "check_point": "Main supply to be checked"},
    {"machine_type": "CO2_MIG", "sr_no": 6, "check_point": "Check the cable between power source to feeder"},
    {"machine_type": "CO2_MIG", "sr_no": 7, "check_point": "Clean up inside of the welding power source"},
    {"machine_type": "CO2_MIG", "sr_no": 8, "check_point": "Ensure volts, current, gas flow, wire flow as per departments"},
    {"machine_type": "CO2_MIG", "sr_no": 9, "check_point": "Ampere and volt meter should be calibrated"},
    {"machine_type": "CO2_MIG", "sr_no": 10, "check_point": "All the nut bolts should be tight properly"},
    # Voltage Stabilizer
    {"machine_type": "VOLTAGE_STABILIZER", "sr_no": 1, "check_point": "Check the loose connection"},
    {"machine_type": "VOLTAGE_STABILIZER", "sr_no": 2, "check_point": "Check the heating of coil and amps"},
    {"machine_type": "VOLTAGE_STABILIZER", "sr_no": 3, "check_point": "Check the cleaning"},
    {"machine_type": "VOLTAGE_STABILIZER", "sr_no": 4, "check_point": "Check the oil level"},
    {"machine_type": "VOLTAGE_STABILIZER", "sr_no": 5, "check_point": "Check the input and output supply"},
    # Control Panel
    {"machine_type": "CONTROL_PANEL", "sr_no": 1, "check_point": "Cleaning of panel to be checked"},
    {"machine_type": "CONTROL_PANEL", "sr_no": 2, "check_point": "Check the loose connection"},
    {"machine_type": "CONTROL_PANEL", "sr_no": 3, "check_point": "Check the amps and volts"},
    {"machine_type": "CONTROL_PANEL", "sr_no": 4, "check_point": "Check the cable hitting"},
    {"machine_type": "CONTROL_PANEL", "sr_no": 5, "check_point": "Check the switch proper on/off condition"},
    # DG Set
    {"machine_type": "DG_SET", "sr_no": 1, "check_point": "Cleaning of DG sets"},
    {"machine_type": "DG_SET", "sr_no": 2, "check_point": "Ensure A, B and C check maintenance"},
    {"machine_type": "DG_SET", "sr_no": 3, "check_point": "Check oil leakage should not occur"},
    {"machine_type": "DG_SET", "sr_no": 4, "check_point": "Check the oil level and oil change date"},
    {"machine_type": "DG_SET", "sr_no": 5, "check_point": "All connections to be checked"},
    {"machine_type": "DG_SET", "sr_no": 6, "check_point": "Check the alternator and output supply"},
    {"machine_type": "DG_SET", "sr_no": 7, "check_point": "Check the ammeter, voltmeter, frequency meter should be ok"},
    # Ovan
    {"machine_type": "OVAN", "sr_no": 1, "check_point": "Cleaning of Ovan and spark plug"},
    {"machine_type": "OVAN", "sr_no": 2, "check_point": "Check the belt, pulley and amps of motor"},
    {"machine_type": "OVAN", "sr_no": 3, "check_point": "Check the main supply and leakage of gas"},
    {"machine_type": "OVAN", "sr_no": 4, "check_point": "Check the Ovan smoke"},
    {"machine_type": "OVAN", "sr_no": 5, "check_point": "Check the Ovan smoke duct"},
    # Arc Machine
    {"machine_type": "ARC_MACHINE", "sr_no": 1, "check_point": "Check the loose connection and main supply"},
    {"machine_type": "ARC_MACHINE", "sr_no": 2, "check_point": "Machine cleaning to be checked"},
    {"machine_type": "ARC_MACHINE", "sr_no": 3, "check_point": "Check the amperes of every machine"},
    {"machine_type": "ARC_MACHINE", "sr_no": 4, "check_point": "Every terminal should be tightened properly"},
    # Blower
    {"machine_type": "BLOWER", "sr_no": 1, "check_point": "Check 440V supply & Amps"},
    {"machine_type": "BLOWER", "sr_no": 2, "check_point": "Check the fan should be clean"},
    {"machine_type": "BLOWER", "sr_no": 3, "check_point": "Nuts and bolts tight properly"},
    {"machine_type": "BLOWER", "sr_no": 4, "check_point": "Check the bearing and amps of motor"},
    {"machine_type": "BLOWER", "sr_no": 5, "check_point": "Every motor greasing to be checked"},
    {"machine_type": "BLOWER", "sr_no": 6, "check_point": "Check the starter switch"},
    {"machine_type": "BLOWER", "sr_no": 7, "check_point": "Blower cotton filter check and change every month"},
    # Hoist
    {"machine_type": "HOIST", "sr_no": 1, "check_point": "Machine should be clean"},
    {"machine_type": "HOIST", "sr_no": 2, "check_point": "Check the connection and main supply"},
    {"machine_type": "HOIST", "sr_no": 3, "check_point": "Check the remote cable and remote"},
    {"machine_type": "HOIST", "sr_no": 4, "check_point": "Check the amps of motor and clutch"},
    {"machine_type": "HOIST", "sr_no": 5, "check_point": "Check the brake of hoist should be tight properly"},
    {"machine_type": "HOIST", "sr_no": 6, "check_point": "All the nut bolts should be properly tight"},
    {"machine_type": "HOIST", "sr_no": 7, "check_point": "Check the wire rope should not break"},
    {"machine_type": "HOIST", "sr_no": 8, "check_point": "Check all limit switches working properly"},
    # Compressor
    {"machine_type": "COMPRESSOR", "sr_no": 1, "check_point": "Check the cleaning"},
    {"machine_type": "COMPRESSOR", "sr_no": 2, "check_point": "Check the oil level, oil filter, and air filter are ok or not"},
    {"machine_type": "COMPRESSOR", "sr_no": 3, "check_point": "Check the loose connection and main supply"},
    {"machine_type": "COMPRESSOR", "sr_no": 4, "check_point": "Check the amp of motor and greasing"},
    {"machine_type": "COMPRESSOR", "sr_no": 5, "check_point": "Check the supply voltage and amp"},
    # Dryer
    {"machine_type": "DRYER", "sr_no": 1, "check_point": "Check the auto drain valve and fan"},
    {"machine_type": "DRYER", "sr_no": 2, "check_point": "Check the main supply"},
    {"machine_type": "DRYER", "sr_no": 3, "check_point": "Check the radiator which is properly clean"},
    {"machine_type": "DRYER", "sr_no": 4, "check_point": "Check the air filter"},
    # Shower
    {"machine_type": "SHOWER", "sr_no": 1, "check_point": "Check the motor, power supply, supply cable"},
    {"machine_type": "SHOWER", "sr_no": 2, "check_point": "Check the amp of motor"},
    {"machine_type": "SHOWER", "sr_no": 3, "check_point": "Check the water nozzle if they break then change them"},
    {"machine_type": "SHOWER", "sr_no": 4, "check_point": "Ensure that the water pressure should be maintained 1.5kg to 2kg"},
    # Plasma Cutter
    {"machine_type": "PLASMA_CUTTER", "sr_no": 1, "check_point": "Check the arc and electrode of head"},
    {"machine_type": "PLASMA_CUTTER", "sr_no": 2, "check_point": "Check the head of plasma cutter"},
    {"machine_type": "PLASMA_CUTTER", "sr_no": 3, "check_point": "Check the cable machine to head"},
    {"machine_type": "PLASMA_CUTTER", "sr_no": 4, "check_point": "Main supply should be proper"},
    {"machine_type": "PLASMA_CUTTER", "sr_no": 5, "check_point": "Check air pressure should be 7.5kg"},
    {"machine_type": "PLASMA_CUTTER", "sr_no": 6, "check_point": "Air pipe should not burst"},
    # IR Lamp
    {"machine_type": "IR_LAMP", "sr_no": 1, "check_point": "Check the incoming supply"},
    {"machine_type": "IR_LAMP", "sr_no": 2, "check_point": "Check the incoming cable"},
    {"machine_type": "IR_LAMP", "sr_no": 3, "check_point": "Check the connection to the IR lamps"},
    {"machine_type": "IR_LAMP", "sr_no": 4, "check_point": "Check the lamp itself"},
    # Shearing M/C
    {"machine_type": "SHEARING_MACHINE", "sr_no": 1, "check_point": "BENDING M/C — Check the motor bearing and amps"},
    {"machine_type": "SHEARING_MACHINE", "sr_no": 2, "check_point": "POWER PRESS — Check the motor greasing"},
    {"machine_type": "SHEARING_MACHINE", "sr_no": 3, "check_point": "ROLLING M/C — Check the supply cable"},
    # Disc Cutter
    {"machine_type": "DISC_CUTTER", "sr_no": 1, "check_point": "TABLE DRILL — Motor bearing and amps to be checked"},
    {"machine_type": "DISC_CUTTER", "sr_no": 2, "check_point": "TABLE GRINDER — Pulley and belt should be checked"},
    {"machine_type": "DISC_CUTTER", "sr_no": 3, "check_point": "Check the greasing of motor"},
    # Electric Grinder
    {"machine_type": "ELECTRIC_GRINDER", "sr_no": 1, "check_point": "ELECTRIC DRILL — Check the switch, armature and field coil"},
    {"machine_type": "ELECTRIC_GRINDER", "sr_no": 2, "check_point": "WOOD CUTTER — Check the cable"},
    {"machine_type": "ELECTRIC_GRINDER", "sr_no": 3, "check_point": "Check the gear, Bearings (608, 629, 6200, 6202)"},
    # CO2 Gas Plant
    {"machine_type": "CO2_GAS_PLANT", "sr_no": 1, "check_point": "Check the leakage of gas pipe"},
    {"machine_type": "CO2_GAS_PLANT", "sr_no": 2, "check_point": "Check the pressure of tank which is 8kg"},
    {"machine_type": "CO2_GAS_PLANT", "sr_no": 3, "check_point": "Check the o/p pressure which is 2kg"},
    {"machine_type": "CO2_GAS_PLANT", "sr_no": 4, "check_point": "Check the proper heating of interior area of gas plant"},
    # Vacuum Cleaner
    {"machine_type": "VACUUM_CLEANER", "sr_no": 1, "check_point": "Check its vacuum to make properly"},
    {"machine_type": "VACUUM_CLEANER", "sr_no": 2, "check_point": "Check the main pipe"},
]


async def seed():
    async with Session() as db:
        now = datetime.now(timezone.utc)

        # Seed assets
        existing_assets = (await db.execute(
            select(MaintenanceAsset.machine_type, MaintenanceAsset.machine_number)
        )).all()
        existing_set = {(r[0], r[1]) for r in existing_assets}

        added_assets = 0
        for a in ASSETS:
            key = (a["machine_type"], a.get("machine_number"))
            if key not in existing_set:
                db.add(MaintenanceAsset(
                    id=uuid.uuid4(),
                    name=a["name"],
                    machine_number=a.get("machine_number"),
                    machine_type=a["machine_type"],
                    year_of_commissioning=a.get("year_of_commissioning"),
                    is_active=True,
                    created_at=now
                ))
                added_assets += 1

        # Seed checklist items
        existing_cl = (await db.execute(
            select(MaintenanceChecklistItem.machine_type, MaintenanceChecklistItem.sr_no)
        )).all()
        existing_cl_set = {(r[0], r[1]) for r in existing_cl}

        added_cl = 0
        for c in CHECKLIST:
            key = (c["machine_type"], c["sr_no"])
            if key not in existing_cl_set:
                db.add(MaintenanceChecklistItem(
                    id=uuid.uuid4(),
                    machine_type=c["machine_type"],
                    sr_no=c["sr_no"],
                    check_point=c["check_point"],
                    specification=c.get("specification"),
                    is_active=True,
                    created_at=now
                ))
                added_cl += 1

        await db.commit()
        print(f"Seeded {added_assets} assets and {added_cl} checklist items.")
        print("Done!")


if __name__ == "__main__":
    asyncio.run(seed())
