#!/usr/bin/env python3
"""
Fix NULL selling prices in SaleItems by calculating them from available data
"""

import sys
from decimal import Decimal
from sqlalchemy import text

# Add app to path
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.core.database import SessionLocal, engine
from app.models.sales import SaleItem, Sale
from app.models.inventory import Product

def fix_null_selling_prices():
    """Find and fix SaleItems with NULL selling_price"""
    db = SessionLocal()

    try:
        # Find all SaleItems with NULL selling_price
        null_items = db.query(SaleItem).filter(SaleItem.selling_price.is_(None)).all()

        if not null_items:
            print("✅ No SaleItems with NULL selling_price found")
            return

        print(f"Found {len(null_items)} SaleItems with NULL selling_price")

        fixed_count = 0
        for item in null_items:
            print(f"\n Processing SaleItem {item.id}")
            print(f"  - Sale: {item.sale_id}")
            print(f"  - Product: {item.product_id}")
            print(f"  - Quantity: {item.quantity}")

            if not item.product:
                print(f"  ❌ Product not found!")
                continue

            # Try to calculate from total_amount if available
            if item.total_amount and item.quantity and item.quantity > 0:
                calculated_price = Decimal(str(item.total_amount)) / Decimal(str(item.quantity))
                print(f"  📊 Calculated selling_price from total_amount: {calculated_price}")
                item.selling_price = calculated_price
                fixed_count += 1
            else:
                # Use product cost_price as fallback
                if item.product.cost_price:
                    margin = Decimal('0.30')  # 30% markup
                    calculated_price = item.product.cost_price * (Decimal('1') + margin)
                    print(f"  📊 Calculated selling_price from cost_price with markup: {calculated_price}")
                    item.selling_price = calculated_price
                    fixed_count += 1
                else:
                    # Default to reasonable amount
                    calculated_price = Decimal('100.00')
                    print(f"  ⚠️  Using default selling price: {calculated_price}")
                    item.selling_price = calculated_price
                    fixed_count += 1

        if fixed_count > 0:
            db.commit()
            print(f"\n✅ Fixed {fixed_count} SaleItems with NULL selling_price")
        else:
            print(f"\n⚠️  Could not fix any items")

    except Exception as e:
        print(f"❌ Error fixing NULL selling prices: {e}")
        db.rollback()
        raise
    finally:
        db.close()

if __name__ == '__main__':
    fix_null_selling_prices()
