#!/usr/bin/env python
"""
Complete fix for inventory accounting entries.
Moves ALL misposted inventory entries from 1400 to 1144.
Moves AP credit entries to proper AP account.
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.core.database import SessionLocal
from app.models.accounting import JournalEntry, AccountingCode
from app.services.accounting_service import AccountingService
from sqlalchemy import text, desc

db = SessionLocal()

print("=" * 80)
print("COMPLETE INVENTORY ACCOUNT CORRECTION")
print("=" * 80)

# Get the accounts
acc_1400 = db.query(AccountingCode).filter(AccountingCode.code == '1400').first()
acc_1144 = db.query(AccountingCode).filter(AccountingCode.code == '1144').first()
acc_2100 = db.query(AccountingCode).filter(AccountingCode.code == '2100').first()  # AP

print(f"\nStarting state:")
print(f"  1400 (WIP): {acc_1400.balance:,.2f}")
print(f"  1144 (Inventory): {acc_1144.balance:,.2f}")
if acc_2100:
    print(f"  2100 (AP): {acc_2100.balance:,.2f}")

# Find all debit entries on 1400 and move them to 1144
print(f"\n{'='*80}")
print("STEP 1: Moving ALL debit entries from 1400 -> 1144")
print('='*80)

debit_entries = db.query(JournalEntry).filter(
    JournalEntry.accounting_code_id == acc_1400.id,
    JournalEntry.debit_amount > 0
).all()

print(f"Found {len(debit_entries)} debit entries on 1400")
total_moved = 0
for entry in debit_entries:
    entry.accounting_code_id = acc_1144.id
    total_moved += entry.debit_amount
    print(f"  ✓ Moved {entry.debit_amount:,.2f}")

print(f"Total debit amount moved: {total_moved:,.2f}")

# Find all credit entries on 1400 and move them to 2100 (AP)
print(f"\n{'='*80}")
print("STEP 2: Moving ALL credit entries from 1400 -> 2100 (AP)")
print('='*80)

credit_entries = db.query(JournalEntry).filter(
    JournalEntry.accounting_code_id == acc_1400.id,
    JournalEntry.credit_amount > 0
).all()

print(f"Found {len(credit_entries)} credit entries on 1400")
total_credit_moved = 0
if acc_2100:
    for entry in credit_entries:
        entry.accounting_code_id = acc_2100.id
        total_credit_moved += entry.credit_amount
        print(f"  ✓ Moved {entry.credit_amount:,.2f}")
    print(f"Total credit amount moved: {total_credit_moved:,.2f}")
else:
    print("  ⚠ Account 2100 (AP) not found - cannot move credit entries")
    print(f"  Keeping credit entries on 1400")

# Commit the moves
db.commit()
print(f"\n✓ All moves committed to database")

# Recalculate balances
print(f"\n{'='*80}")
print("STEP 3: Recalculating account balances")
print('='*80)

service = AccountingService(db)

print("  Recalculating 1400...")
service.update_account_balance(acc_1400.id)
print("  Recalculating 1144...")
service.update_account_balance(acc_1144.id)
if acc_2100:
    print("  Recalculating 2100...")
    service.update_account_balance(acc_2100.id)

# Reload and display final state
db.refresh(acc_1400)
db.refresh(acc_1144)
if acc_2100:
    db.refresh(acc_2100)

print(f"\n{'='*80}")
print("FINAL STATE")
print('='*80)
print(f"  1400 (WIP): {acc_1400.balance:,.2f}")
print(f"  1144 (Inventory): {acc_1144.balance:,.2f}")
if acc_2100:
    print(f"  2100 (AP): {acc_2100.balance:,.2f}")

# Verify debit/credit entries
print(f"\n{'='*80}")
print("VERIFICATION")
print('='*80)

remaining_on_1400 = db.query(JournalEntry).filter(
    JournalEntry.accounting_code_id == acc_1400.id
).all()

print(f"Entries remaining on 1400: {len(remaining_on_1400)}")
if remaining_on_1400:
    for entry in remaining_on_1400:
        print(f"  - Debit: {entry.debit_amount}, Credit: {entry.credit_amount}")

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