#!/usr/bin/env python
"""
Enhanced sales GL posting service
"""
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.sales import Invoice, InvoiceItem, Payment
from app.models.accounting import AccountingCode, JournalEntry, AccountingEntry
from app.models.inventory import Product
from app.models.banking import BankAccount
from decimal import Decimal
from datetime import datetime, date
from sqlalchemy import func, inspect

db = SessionLocal()

print("=" * 80)
print("ENHANCED SALES GL POSTING ANALYSIS")
print("=" * 80)

# Check InvoiceItem structure
print("\n1. InvoiceItem model columns:")
mapper = inspect(InvoiceItem)
columns = [c.name for c in mapper.columns]
print(f"   Columns: {columns}")
print(f"   Has cost_price: {'cost_price' in columns}")

# Sample invoice analysis
print("\n2. Sample Invoice Analysis:")
sample = db.query(Invoice).first()
if sample:
    print(f"   Invoice: {sample.invoice_number}")
    print(f"   Total: {sample.total_amount}")
    print(f"   Items: {len(sample.invoice_items)}")

    if sample.invoice_items:
        item = sample.invoice_items[0]
        print(f"\n   Item 0:")
        print(f"   - Product ID: {item.product_id}")
        print(f"   - Quantity: {item.quantity}")
        print(f"   - Price: {item.price}")

        if item.product_id:
            prod = db.query(Product).filter(Product.id == item.product_id).first()
            if prod:
                print(f"   - Product Cost: {prod.cost_price}")
                print(f"   - GL Account: {prod.accounting_code_id}")

                if prod.accounting_code_id:
                    acc = db.query(AccountingCode).filter(
                        AccountingCode.id == prod.accounting_code_id
                    ).first()
                    if acc:
                        print(f"     GL Code: {acc.code} - {acc.name}")

# Check GL accounts
print("\n3. GL Accounts:")
cogs = db.query(AccountingCode).filter(AccountingCode.code == '5000').first()
if cogs:
    print(f"   COGS (5000): {cogs.name}")

prods_gl = db.query(Product).filter(
    Product.accounting_code_id.isnot(None),
    Product.quantity > 0
).count()
print(f"   Products with GL accounts: {prods_gl}")

# Check payments
print("\n4. Payment GL Structure:")
pmts = db.query(Payment).count()
print(f"   Payments in DB: {pmts}")

pmt = db.query(Payment).first()
if pmt:
    print(f"   Sample payment fields:")
    print(f"   - invoice_id: {pmt.invoice_id}")
    print(f"   - amount: {pmt.amount}")
    print(f"   - bank_account_id: {pmt.bank_account_id}")

    if pmt.bank_account_id:
        ba = db.query(BankAccount).filter(BankAccount.id == pmt.bank_account_id).first()
        if ba:
            print(f"   - Bank GL Code: {ba.accounting_code_id}")

print("\n" + "=" * 80)
print("READY FOR POST_SALE_TO_ACCOUNTING ENHANCEMENT")
print("=" * 80)

db.close()
