#!/usr/bin/env python3
"""
Create Missing GL Accounts

Creates the 21 missing GL accounts that are needed for the item type routing system.
These accounts are defined in the GLAccountMapping but don't exist in the database.
"""

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

from decimal import Decimal

# Import accounting after path setup
from app.core.database import SessionLocal
from app.models.accounting import AccountingCode


def main():
    db = SessionLocal()
    print("\n" + "="*80)
    print("CREATE MISSING GL ACCOUNTS")
    print("="*80)

    # Define the missing GL accounts
    # Format: (code, name, account_type, category)
    missing_accounts = [
        # Inventory accounts
        ("1105", "Raw Materials", "Asset", "Inventory"),
        ("1115", "Finished Goods", "Asset", "Inventory"),

        # Fixed Asset accounts
        ("1150", "Prepaid Expenses", "Asset", "Current Asset"),
        ("1155", "Rental Deposits", "Asset", "Current Asset"),
        ("1201", "Buildings & Leasehold", "Asset", "Fixed Asset"),
        ("1205", "Machinery", "Asset", "Fixed Asset"),
        ("1215", "Furniture & Fixtures", "Asset", "Fixed Asset"),
        ("1230", "Computers & Equipment", "Asset", "Fixed Asset"),

        # Intangible Asset accounts
        ("1301", "Patents & Trademarks", "Asset", "Intangible Assets"),
        ("1305", "Licenses & Franchises", "Asset", "Intangible Assets"),
        ("1315", "Software", "Asset", "Intangible Assets"),

        # Expense accounts
        ("5010", "General Expenses", "Expense", "Supplies"),
        ("5020", "Office Supplies", "Expense", "Supplies"),
        ("5030", "Consumables", "Expense", "Supplies"),
        ("5040", "Maintenance & Repairs", "Expense", "Maintenance"),
        ("5050", "Professional Services", "Expense", "Service"),
        ("5060", "Travel Expenses", "Expense", "Travel"),
        ("5070", "Insurance Expense", "Expense", "Insurance"),
        ("5080", "Rent and Lease", "Expense", "Rent"),
        ("5090", "Advertising & Marketing", "Expense", "Marketing"),
        ("5900", "Miscellaneous Expense", "Expense", "Miscellaneous"),
    ]

    created_count = 0
    failed_accounts = []

    for code, name, account_type, category in missing_accounts:
        # Check if already exists
        existing = db.query(AccountingCode).filter(
            AccountingCode.code == code
        ).first()

        if existing:
            print(f"[EXIST] {code:6} - {name:35} (already in DB)")
            continue

        try:
            # Create the account
            account = AccountingCode(
                code=code,
                name=name,
                account_type=account_type,
                category=category,
                total_debits=Decimal("0"),
                total_credits=Decimal("0"),
                balance=Decimal("0"),
                currency="PHP",
                is_parent=False,
                is_dimensional_template=False,
                sort_order=int(code)
            )
            db.add(account)
            db.commit()
            print(f"[OK   ] {code:6} - {name:35} ({category})")
            created_count += 1

        except Exception as e:
            db.rollback()
            print(f"[ERROR] {code:6} - {name:35} - {str(e)}")
            failed_accounts.append((code, str(e)))

    # Summary
    print("\n" + "="*80)
    print(f"SUMMARY: Created {created_count} GL accounts")

    if failed_accounts:
        print(f"\n{len(failed_accounts)} accounts failed:")
        for code, error in failed_accounts:
            print(f"  - {code}: {error}")

    # Final count
    final_count = db.query(AccountingCode).count()
    print(f"\nTotal GL accounts in database: {final_count}")
    print(f"(Before: ~{final_count - created_count}, Created: {created_count})")

    print("\n" + "="*80)
    print("Next: Run 'python scripts/complete_seed_item_types.py' to link item types")
    print("="*80 + "\n")

    db.close()
    return len(failed_accounts) == 0


if __name__ == "__main__":
    try:
        success = main()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"\n[FATAL] {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
