#!/usr/bin/env python3
"""
Fix Machine Types from Inventory Data
Updates machines with incorrect machinetypeid based on equipment names/descriptions
"""

import csv
import re
import pymysql

# Database connection settings
DB_CONFIG = {
    'host': 'localhost',
    'user': '570005354',
    'password': '570005354',
    'database': 'shopdb',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}

# Machine type mapping rules based on equipment names/keywords
MACHINE_TYPE_RULES = [
    # CMMs (Coordinate Measuring Machines)
    (r'(?i)(CMM|Hexagon|Brown.?Sharpe|Mitutoyo C\s*\d+)', 'CMM'),

    # Vertical Lathes (expanded patterns for OKUMA machines)
    (r'(?i)(VT\s*\d+|VTL\s*\d+|VT\s*5502|Vertical.*Lathe|Hwacheon.*V|2SP.*V\d+|VTM\s*\d+|OKUMA.*V\d+)', 'Vertical Lathe'),

    # Regular Lathes
    (r'(?i)((?<!Vertical\s)Lathe|Turning|LB\s*\d+)', 'Lathe'),

    # Mill Turn
    (r'(?i)(Mill.*Turn|Multitasking)', 'Mill Turn'),

    # 5-axis Mills
    (r'(?i)(5.?axis|Five.?axis)', '5-axis Mill'),

    # Grinders
    (r'(?i)(Grind|Surface.*Grind)', 'Grinder'),

    # Part Washers
    (r'(?i)(Washer|Wash.*Station|Cleaning)', 'Part Washer'),

    # Furnaces
    (r'(?i)(Furnace|Oven|Heat.*Treat)', 'Furnace'),

    # EDM/Eddy Current
    (r'(?i)(EDM|Eddy.*Current)', 'Eddy Current'),

    # Welders
    (r'(?i)(Weld|Intertia)', 'Intertia Welder'),

    # Measuring Machines (generic)
    (r'(?i)(Measur|Inspect.*Machine)', 'Measuring Machine'),

    # Keyence Vision Systems
    (r'(?i)(Keyence|VHX|VR\s*\d+)', 'Measuring Machine'),

    # Hobbing
    (r'(?i)(Hobb|Gear.*Cut)', 'Hobbing Machine'),

    # Deburring
    (r'(?i)(Deburr|Polish)', 'Robotic Deburring'),

    # Shot Peen
    (r'(?i)(Shot.?peen|Peen)', 'Shotpeen'),

    # Broach
    (r'(?i)(Broach)', 'Broach'),
]

def connect_db():
    """Connect to MySQL database"""
    try:
        conn = pymysql.connect(**DB_CONFIG)
        print(f"✓ Connected to database: {DB_CONFIG['database']}")
        return conn
    except Exception as e:
        print(f"✗ Database connection failed: {e}")
        return None

def get_machine_type_id(cursor, machine_type_name):
    """Get machine type ID by name"""
    cursor.execute(
        "SELECT machinetypeid FROM machinetypes WHERE machinetype = %s",
        (machine_type_name,)
    )
    result = cursor.fetchone()
    return result['machinetypeid'] if result else None

def determine_machine_type(equipment_name):
    """Determine correct machine type based on equipment name"""
    if not equipment_name:
        return None

    # Check each rule
    for pattern, machine_type in MACHINE_TYPE_RULES:
        if re.search(pattern, equipment_name):
            return machine_type

    return None

def update_machine_type_from_inventory(cursor, conn):
    """Update machine types based on inventory data"""

    # Read inventory CSV
    csv_file = '/tmp/inventory_restructured.csv'
    print(f"\n📄 Reading inventory: {csv_file}")

    with open(csv_file, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        equipment_rows = [row for row in reader if row.get('Row_Type') == 'Equipment']

    print(f"✓ Found {len(equipment_rows)} equipment records")

    # Get LocationOnly machine type ID
    location_only_id = get_machine_type_id(cursor, 'LocationOnly')
    print(f"✓ LocationOnly machine type ID: {location_only_id}")

    updates_made = 0
    skipped = 0
    errors = 0

    print("\n" + "="*70)
    print("UPDATING MACHINE TYPES")
    print("="*70)

    for row in equipment_rows:
        machine_number = row.get('Machine_Number', '').strip()
        equipment_name = row.get('Equipment_Name', '').strip()

        if not machine_number or not equipment_name:
            continue

        # Check if machine exists and is LocationOnly
        cursor.execute(
            """SELECT m.machineid, m.machinetypeid, mt.machinetype, m.alias
               FROM machines m
               JOIN machinetypes mt ON m.machinetypeid = mt.machinetypeid
               WHERE m.machinenumber = %s AND m.isactive = 1""",
            (machine_number,)
        )
        machine = cursor.fetchone()

        if not machine:
            continue

        # Determine correct machine type from equipment name
        correct_type_name = determine_machine_type(equipment_name)

        if not correct_type_name:
            skipped += 1
            continue

        correct_type_id = get_machine_type_id(cursor, correct_type_name)

        if not correct_type_id:
            print(f"  ⚠️  Machine type '{correct_type_name}' not found in database")
            errors += 1
            continue

        # Only update if currently LocationOnly or wrong type
        if machine['machinetypeid'] == location_only_id or machine['machinetypeid'] != correct_type_id:
            print(f"\n🔧 Machine {machine_number}: {equipment_name}")
            print(f"   Current: {machine['machinetype']} (ID: {machine['machinetypeid']})")
            print(f"   New:     {correct_type_name} (ID: {correct_type_id})")

            cursor.execute(
                "UPDATE machines SET machinetypeid = %s, lastupdated = NOW() WHERE machineid = %s",
                (correct_type_id, machine['machineid'])
            )
            conn.commit()
            updates_made += 1
            print(f"   ✓ Updated")
        else:
            skipped += 1

    return updates_made, skipped, errors

def main():
    """Main process"""
    print("="*70)
    print("MACHINE TYPE CORRECTION SCRIPT")
    print("="*70)

    conn = connect_db()
    if not conn:
        return

    cursor = conn.cursor()

    # Show current LocationOnly count
    cursor.execute(
        """SELECT COUNT(*) as count FROM machines m
           JOIN machinetypes mt ON m.machinetypeid = mt.machinetypeid
           WHERE mt.machinetype = 'LocationOnly' AND m.isactive = 1"""
    )
    before_count = cursor.fetchone()['count']
    print(f"\n📊 Current LocationOnly machines: {before_count}")

    # Update machine types from inventory
    updates, skipped, errors = update_machine_type_from_inventory(cursor, conn)

    # Show after count
    cursor.execute(
        """SELECT COUNT(*) as count FROM machines m
           JOIN machinetypes mt ON m.machinetypeid = mt.machinetypeid
           WHERE mt.machinetype = 'LocationOnly' AND m.isactive = 1"""
    )
    after_count = cursor.fetchone()['count']

    # Summary
    print("\n" + "="*70)
    print("SUMMARY")
    print("="*70)
    print(f"LocationOnly machines before: {before_count}")
    print(f"LocationOnly machines after:  {after_count}")
    print(f"Machines updated:             {updates}")
    print(f"Machines skipped:             {skipped}")
    print(f"Errors:                       {errors}")
    print(f"Net reduction:                {before_count - after_count}")

    # Show breakdown by machine type now
    print("\n" + "="*70)
    print("MACHINE TYPE DISTRIBUTION (Top 15)")
    print("="*70)
    cursor.execute(
        """SELECT mt.machinetype, COUNT(*) as count
           FROM machines m
           JOIN machinetypes mt ON m.machinetypeid = mt.machinetypeid
           WHERE m.isactive = 1
           GROUP BY m.machinetypeid
           ORDER BY count DESC
           LIMIT 15"""
    )

    for row in cursor.fetchall():
        print(f"{row['machinetype']:30} {row['count']:4}")

    cursor.close()
    conn.close()

    print("\n✓ Complete!")

if __name__ == '__main__':
    main()
