from django.db import models
from django.core.files.base import ContentFile
from django.utils import timezone
from taggit.managers import TaggableManager

# Bank account model


class BankAccount(models.Model):
    account_nickname = models.CharField(max_length=255, blank=True)
    institution_name = models.CharField(max_length=255)
    street_1 = models.CharField(max_length=255, blank=True)
    street_2 = models.CharField(max_length=255, blank=True)
    city = models.CharField(max_length=255, blank=True)
    phone = models.CharField(max_length=50, blank=True)
    routing_number = models.CharField(max_length=20)
    account_number = models.CharField(max_length=20)
    payor_name = models.CharField(max_length=255, blank=True)
    payor_street_1 = models.CharField(max_length=255, blank=True)
    payor_street_2 = models.CharField(max_length=255, blank=True)
    payor_city = models.CharField(max_length=255, blank=True)
    payor_phone = models.CharField(max_length=50, blank=True)

    def save(self, *args, **kwargs):
        if not self.account_nickname:
            self.account_nickname = self.institution_name
        super().save(*args, **kwargs)

    def __str__(self):
        return (
            f"{self.account_nickname or self.institution_name} ({self.account_number})"
        )


# Payee model


class Payee(models.Model):
    name = models.CharField(max_length=255)
    street_1 = models.CharField(max_length=255, blank=True)
    street_2 = models.CharField(max_length=255, blank=True)
    city = models.CharField(max_length=255, blank=True)
    payor_account_number = models.CharField(max_length=20, blank=True)

    def __str__(self):
        return self.name


# Check model
class Check(models.Model):
    bank_account = models.ForeignKey(BankAccount, on_delete=models.CASCADE)
    payee = models.ForeignKey(Payee, on_delete=models.CASCADE)
    category = models.ForeignKey(
        "Category", on_delete=models.SET_NULL, blank=True, null=True
    )
    check_number = models.PositiveIntegerField(unique=True, editable=False)
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    memo = models.CharField(max_length=255, blank=True)
    invoice = models.CharField(max_length=255, blank=True)
    check_date = models.DateField(default=timezone.now)
    pdf = models.FileField(upload_to="checks/", blank=True, null=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    tags = TaggableManager(blank=True)

    def __str__(self):
        return f"Check #{self.check_number} to {self.payee}"

    def save(self, *args, **kwargs):
        # Auto-generate unique check_number if not set
        if not self.check_number:
            last = Check.objects.order_by("-check_number").first()
            self.check_number = (last.check_number + 1) if last else 1
        super().save(*args, **kwargs)
        from .helpers import generate_check_pdf

        pdf_content = generate_check_pdf(self)
        filename = f"check_{self.pk}.pdf"
        self.pdf.save(filename, ContentFile(pdf_content), save=False)
        super().save(*args, **kwargs)

    @staticmethod
    def export_to_monarchmoney_csv(queryset):
        """
        Export selected checks as MonarchMoney-compatible CSV.
        Returns a tuple: (filename, csv_content)
        """
        import csv
        import io

        output = io.StringIO()
        writer = csv.writer(output)
        writer.writerow(
            [
                "Date",
                "Merchant",
                "Category",
                "Account",
                "Original Statement",
                "Notes",
                "Amount",
                "Tags",
            ]
        )
        for check in queryset:
            date = check.check_date.strftime("%Y-%m-%d")
            merchant = check.payee.name
            category = check.category.name if check.category else ""
            account = (
                check.bank_account.account_nickname
                or check.bank_account.institution_name
            )
            original_statement = (
                f"{check.payee.name} - {check.payee.payor_account_number}"
            )
            notes = f"{check.check_number} - {check.payee.name} - {check.payee.payor_account_number} - {check.memo} - {check.invoice}"
            amount = f"{check.amount:.2f}"
            tags = (
                ", ".join(tag.name for tag in check.tags.all())
                if hasattr(check, "tags")
                else ""
            )
            writer.writerow(
                [
                    date,
                    merchant,
                    category,
                    account,
                    original_statement,
                    notes,
                    amount,
                    tags,
                ]
            )
        filename = "checks_monarchmoney.csv"
        csv_content = output.getvalue()
        output.close()
        return filename, csv_content


# Category model
class Category(models.Model):
    name = models.CharField(max_length=100, unique=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Categories"
        ordering = ["name"]
