import os

path = 'core/models.py'
with open(path, 'r') as f:
    content = f.read()

# Patch SalePayment
old_sale_payment = """    notes = models.TextField(_("Notes"), blank=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name="sale_payments")

    def __str__(self):"""
new_sale_payment = """    notes = models.TextField(_("Notes"), blank=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name="sale_payments")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):"""

# Patch PurchasePayment
old_purchase_payment = """    notes = models.TextField(_("Notes"), blank=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name="purchase_payments")

    def __str__(self):"""
new_purchase_payment = """    notes = models.TextField(_("Notes"), blank=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name="purchase_payments")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):"""

# Check if SalePayment already has created_at
# A simple check: if we find the new pattern, we skip
if new_sale_payment in content:
    print("SalePayment already patched.")
else:
    content = content.replace(old_sale_payment, new_sale_payment)

if new_purchase_payment in content:
    print("PurchasePayment already patched.")
else:
    content = content.replace(old_purchase_payment, new_purchase_payment)

with open(path, 'w') as f:
    f.write(content)
print("Patched core/models.py")
