#!/usr/bin/env python3
"""
Simplified seed script to populate item_type_definitions with existing GL accounts

This version links to existing GL accounts without creating new ones
"""

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

from app.core.database import SessionLocal
from app.models.item_type_mapping import ItemTypeEnum, GLAccountMapping, ItemTypeDefinition
from app.models.accounting import AccountingCode


def seed_item_type_definitions():
    """
    Seed the item_type_definitions table with all standard item types,
    using existing GL accounts from the accounting_codes table
    """

    db = SessionLocal()

    try:
        print("\n" + "=" * 80)
        print("SEEDING ITEM TYPE DEFINITIONS (SIMPLIFIED)")
        print("=" * 80)

        # Check if already seeded
        existing_count = db.query(ItemTypeDefinition).count()
        if existing_count > 0:
            print(f"\n[INFO] Found {existing_count} existing item type definitions")
            response = input("Do you want to clear and reseed? (y/n): ").strip().lower()
            if response == 'y':
                print(f"Deleting {existing_count} existing definitions...")
                db.query(ItemTypeDefinition).delete()
                db.commit()
            else:
                print("Skipping seed operation")
                return

        # Get all GL account mappings
        mappings = GLAccountMapping.MAPPING

        print(f"\nProcessing {len(mappings)} item types...\n")

        created_count = 0
        skipped = []

        for item_type, mapping_dict in mappings.items():
            description = mapping_dict.get('description', item_type)
            debit_code = mapping_dict.get('debit_account')

            # Try to find the debit account
            debit_account = db.query(AccountingCode).filter(
                AccountingCode.code == debit_code
            ).first()

            if not debit_account:
                skipped.append(f"{item_type} (GL code {debit_code} not found)")
                continue

            print(f"  [{created_count + 1}/28] {item_type:30} -> GL {debit_code} ({debit_account.name})")

            # Create ItemTypeDefinition (MINIMAL - only required fields)
            item_type_def = ItemTypeDefinition(
                id=f"item-type-{item_type}",  # Use deterministic IDs
                item_type=item_type,
                name=description,
                description=description,
                debit_account_id=debit_account.id,
                is_asset=mapping_dict.get('is_asset', False),
                is_taxable=mapping_dict.get('is_taxable', True),
                requires_serial_number=mapping_dict.get('requires_serial_number', False),
                is_active=True,
                useful_life_years=mapping_dict.get('useful_life_years', None),
            )

            db.add(item_type_def)
            created_count += 1

        # Commit all changes
        db.commit()

        print("\n" + "=" * 80)
        print(f"[OK] SUCCESSFULLY SEEDED {created_count} ITEM TYPE DEFINITIONS")
        print("=" * 80)

        if skipped:
            print(f"\n[WARNING] Skipped {len(skipped)} item types (GL accounts not found):")
            for item in skipped:
                print(f"  - {item}")

        # Display summary
        print("\nItem types created:")
        definitions = db.query(ItemTypeDefinition).order_by(ItemTypeDefinition.item_type).all()
        for defn in definitions:
            debit_code = defn.debit_account.code if defn.debit_account else '????'
            print(f"    • {defn.item_type:35} ({debit_code:>5}) - {defn.name}")

        print("\n" + "=" * 80 + "\n")

    except Exception as e:
        db.rollback()
        print(f"\n[ERROR] ERROR: {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

    finally:
        db.close()


if __name__ == "__main__":
    seed_item_type_definitions()
