# ============================================================
# File: app/routes/purchase.py
# ============================================================
import os
from datetime import date
from decimal import Decimal

from flask import (
    Blueprint,
    current_app,
    flash,
    redirect,
    render_template,
    request,
    session,
    url_for,
)
from werkzeug.utils import secure_filename

from app.extensions import db
from app.models.accounting import (
    AccountGroup,
    AccountLedger,
    HSNMaster,
    PurchaseInvoice,
    PurchaseInvoiceItem,
    TDSSection,
    Vendor,
    VendorGSTIN,
    Voucher,
    VoucherType,PurchasePaymentAllocation
)
from app.services.gst_service import GSTService
from app.services.posting_engine import PostingEngine, PostingError
from app.utils.permissions import current_company_id, login_required, permission_required


purchase_bp = Blueprint("purchase", __name__, url_prefix="/purchase")


ALLOWED_PURCHASE_ATTACHMENTS = {"pdf", "png", "jpg", "jpeg", "webp"}


def money(value):
    if value in [None, ""]:
        return Decimal("0.00")
    return Decimal(str(value)).quantize(Decimal("0.01"))


def allowed_purchase_attachment(filename):
    return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_PURCHASE_ATTACHMENTS


def save_purchase_attachment(file_storage, bill_no):
    if not file_storage or not file_storage.filename:
        return None

    if not allowed_purchase_attachment(file_storage.filename):
        raise ValueError("Only PDF, PNG, JPG, JPEG and WEBP files are allowed.")

    filename = secure_filename(file_storage.filename)
    ext = filename.rsplit(".", 1)[1].lower()
    final_filename = f"{bill_no}_{date.today().isoformat()}.{ext}"

    upload_dir = os.path.join(
        current_app.root_path,
        "static",
        "uploads",
        "purchase_bills",
    )
    os.makedirs(upload_dir, exist_ok=True)

    file_path = os.path.join(upload_dir, final_filename)
    file_storage.save(file_path)

    return f"uploads/purchase_bills/{final_filename}"


def next_purchase_bill_no(company_id):
    count = PurchaseInvoice.query.filter_by(company_id=company_id).count() + 1
    return f"PI-{str(count).zfill(5)}"


def get_purchase_expense_ledgers(company_id):
    return (
        AccountLedger.query.join(AccountLedger.group)
        .filter(
            AccountLedger.company_id == company_id,
            AccountLedger.is_deleted.is_(False),
            AccountLedger.active.isnot(False),
            AccountLedger.group.has(nature="expense"),
        )
        .order_by(AccountLedger.ledger_name)
        .all()
    )

def get_or_create_tds_payable_ledger(company_id):
    group = AccountGroup.query.filter_by(
        company_id=company_id,
        group_name="Duties & Taxes",
        is_deleted=False,
    ).first()

    if not group:
        group = AccountGroup.query.filter_by(
            company_id=company_id,
            group_name="Current Liabilities",
            is_deleted=False,
        ).first()

    if not group:
        raise ValueError("Duties & Taxes or Current Liabilities group not found. Please seed default account groups.")

    ledger = AccountLedger.query.filter_by(
        company_id=company_id,
        ledger_name="TDS Payable",
        is_deleted=False,
    ).first()

    if ledger:
        return ledger

    ledger = AccountLedger(
        company_id=company_id,
        ledger_code="TDS-PAY",
        ledger_name="TDS Payable",
        group_id=group.id,
        ledger_type="tax",
        opening_balance=0,
        opening_balance_type="cr",
        gst_applicable=False,
        tds_applicable=True,
        bill_wise_enabled=False,
        cost_center_enabled=False,
        branch_wise_enabled=False,
    )
    db.session.add(ledger)
    db.session.flush()
    return ledger

def get_or_create_tax_ledger(company_id, ledger_name, ledger_code):
    group = AccountGroup.query.filter_by(
        company_id=company_id,
        group_name="Duties & Taxes",
        is_deleted=False,
    ).first()

    if not group:
        group = AccountGroup.query.filter_by(
            company_id=company_id,
            group_name="Current Liabilities",
            is_deleted=False,
        ).first()

    if not group:
        raise ValueError("Duties & Taxes or Current Liabilities group not found. Please seed default account groups.")

    ledger = AccountLedger.query.filter_by(
        company_id=company_id,
        ledger_name=ledger_name,
        is_deleted=False,
    ).first()

    if ledger:
        return ledger

    ledger = AccountLedger(
        company_id=company_id,
        ledger_code=ledger_code,
        ledger_name=ledger_name,
        group_id=group.id,
        ledger_type="tax",
        opening_balance=0,
        opening_balance_type="cr",
        gst_applicable=True,
        tds_applicable=False,
        bill_wise_enabled=False,
        cost_center_enabled=False,
        branch_wise_enabled=False,
    )
    db.session.add(ledger)
    db.session.flush()
    return ledger

def get_purchase_form_data(company_id):
    vendors = (
        Vendor.query.filter(
            Vendor.company_id == company_id,
            Vendor.is_deleted.is_(False),
            Vendor.active.isnot(False),
        )
        .order_by(Vendor.vendor_name)
        .all()
    )

    expense_ledgers = get_purchase_expense_ledgers(company_id)

    hsn_codes = (
        HSNMaster.query.filter_by(active=True)
        .order_by(HSNMaster.hsn_code)
        .all()
    )

    tds_sections = (
        TDSSection.query.filter_by(active=True)
        .order_by(TDSSection.section_code)
        .all()
    )

    return vendors, expense_ledgers, hsn_codes, tds_sections

def selected_vendor_gstin(company_id, vendor_id, vendor_gstin_id):
    if vendor_gstin_id:
        row = VendorGSTIN.query.filter_by(
            id=vendor_gstin_id,
            company_id=company_id,
            vendor_id=vendor_id,
            active=True,
        ).first()
        if row:
            return row

    return VendorGSTIN.query.filter_by(
        company_id=company_id,
        vendor_id=vendor_id,
        is_default=True,
        active=True,
    ).first()

def build_purchase_posting_entries(
    company_id,
    vendor,
    bill_no,
    items,
    total_cgst,
    total_sgst,
    total_igst,
    round_off_amount,
    total_amount,
    gst_type,
    tds_amount=Decimal("0.00"),
):
    gst_service = GSTService(company_id)

    entries = []
    ledger_totals = {}

    for item in items:
        ledger_id = item["expense_ledger_id"]
        ledger_totals[ledger_id] = ledger_totals.get(ledger_id, Decimal("0.00")) + item["taxable_amount"]

    for ledger_id, amount in ledger_totals.items():
        entries.append(
            {
                "ledger_id": ledger_id,
                "debit_amount": amount,
                "credit_amount": 0,
                "line_narration": f"Purchase bill {bill_no}",
            }
        )

    if gst_type == "regular":
        if total_cgst > 0:
            entries.append(
                {
                    "ledger_id": gst_service.input_cgst_ledger().id,
                    "debit_amount": total_cgst,
                    "credit_amount": 0,
                    "line_narration": f"Input CGST on {bill_no}",
                }
            )

        if total_sgst > 0:
            entries.append(
                {
                    "ledger_id": gst_service.input_sgst_ledger().id,
                    "debit_amount": total_sgst,
                    "credit_amount": 0,
                    "line_narration": f"Input SGST on {bill_no}",
                }
            )

        if total_igst > 0:
            entries.append(
                {
                    "ledger_id": gst_service.input_igst_ledger().id,
                    "debit_amount": total_igst,
                    "credit_amount": 0,
                    "line_narration": f"Input IGST on {bill_no}",
                }
            )

    elif gst_type == "igst":
        if total_igst > 0:
            entries.append(
                {
                    "ledger_id": gst_service.input_igst_ledger().id,
                    "debit_amount": total_igst,
                    "credit_amount": 0,
                    "line_narration": f"Input IGST on {bill_no}",
                }
            )

    elif gst_type == "rcm":
        if total_cgst > 0:
            entries.append({
                "ledger_id": gst_service.input_cgst_ledger().id,
                "debit_amount": total_cgst,
                "credit_amount": 0,
                "line_narration": f"Input CGST under RCM on {bill_no}",
            })
            entries.append({
                "ledger_id": get_or_create_tax_ledger(company_id, "RCM CGST Payable", "RCM-CGST").id,
                "debit_amount": 0,
                "credit_amount": total_cgst,
                "line_narration": f"RCM CGST payable on {bill_no}",
            })

        if total_sgst > 0:
            entries.append({
                "ledger_id": gst_service.input_sgst_ledger().id,
                "debit_amount": total_sgst,
                "credit_amount": 0,
                "line_narration": f"Input SGST under RCM on {bill_no}",
            })
            entries.append({
                "ledger_id": get_or_create_tax_ledger(company_id, "RCM SGST Payable", "RCM-SGST").id,
                "debit_amount": 0,
                "credit_amount": total_sgst,
                "line_narration": f"RCM SGST payable on {bill_no}",
            })

        if total_igst > 0:
            entries.append({
                "ledger_id": gst_service.input_igst_ledger().id,
                "debit_amount": total_igst,
                "credit_amount": 0,
                "line_narration": f"Input IGST under RCM on {bill_no}",
            })
            entries.append({
                "ledger_id": get_or_create_tax_ledger(company_id, "RCM IGST Payable", "RCM-IGST").id,
                "debit_amount": 0,
                "credit_amount": total_igst,
                "line_narration": f"RCM IGST payable on {bill_no}",
            })

    elif gst_type in ["exempt", "non_gst", "pure_agent"]:
        # No GST ledger posting.
        pass

    if round_off_amount != 0 and entries:
        entries[0]["debit_amount"] = money(entries[0]["debit_amount"]) + round_off_amount

    if gst_type == "rcm":
        rcm_tax = money(total_cgst) + money(total_sgst) + money(total_igst)
        vendor_payable_amount = total_amount - rcm_tax - money(tds_amount)
    else:
        vendor_payable_amount = total_amount - money(tds_amount)

    if money(tds_amount) > 0:
        tds_ledger = get_or_create_tds_payable_ledger(company_id)
        entries.append(
            {
                "ledger_id": tds_ledger.id,
                "debit_amount": 0,
                "credit_amount": money(tds_amount),
                "line_narration": f"TDS deducted on {bill_no}",
            }
        )

    entries.append(
        {
            "ledger_id": vendor.ledger_id,
            "debit_amount": 0,
            "credit_amount": vendor_payable_amount,
            "line_narration": f"Purchase bill {bill_no}",
            "party_type": "vendor",
            "party_id": vendor.id,
            "bill_ref_no": bill_no,
            "bill_ref_type": "purchase_invoice",
        }
    )

    return entries


@purchase_bp.route("/invoices")
@login_required
@permission_required("accounts.view")
def invoices():
    company_id = current_company_id()
    invoices = (
        PurchaseInvoice.query.filter_by(company_id=company_id, is_deleted=False)
        .order_by(PurchaseInvoice.bill_date.desc(), PurchaseInvoice.id.desc())
        .all()
    )
    return render_template("purchase/invoices.html", invoices=invoices)


@purchase_bp.route("/invoices/add", methods=["GET", "POST"])
@login_required
@permission_required("vouchers.create")
def add_invoice():
    company_id = current_company_id()
    vendors, expense_ledgers, hsn_codes, tds_sections = get_purchase_form_data(company_id)

    if request.method == "POST":
        vendor_id = request.form.get("vendor_id", type=int)
        bill_no = request.form.get("bill_no") or next_purchase_bill_no(company_id)

        vendor_gstin_id = request.form.get("vendor_gstin_id", type=int)

        entry_date = date.fromisoformat(request.form.get("entry_date"))
        posting_date = date.fromisoformat(request.form.get("posting_date"))
        bill_date = date.fromisoformat(request.form.get("bill_date"))

        vendor_invoice_no = request.form.get("vendor_invoice_no")
        reference_no = request.form.get("reference_no")
        narration = request.form.get("narration")
        gst_type = request.form.get("gst_type") or "regular"
        currency_code = request.form.get("currency_code") or "INR"
        exchange_rate = money(request.form.get("exchange_rate") or 1)

        tds_applicable = bool(request.form.get("tds_applicable"))
        tds_section_id = request.form.get("tds_section_id", type=int)
        tds_rate = money(request.form.get("tds_rate") or 0)

        is_draft = posting_date > date.today()

        vendor = Vendor.query.filter_by(
            id=vendor_id,
            company_id=company_id,
            is_deleted=False,
        ).first()

        if not vendor:
            flash("Please select a valid vendor.", "danger")
            return redirect(url_for("purchase.add_invoice"))
        
        vendor_gstin_row = selected_vendor_gstin(company_id, vendor.id, vendor_gstin_id)
        vendor_state_for_gst = vendor_gstin_row.state if vendor_gstin_row and vendor_gstin_row.state else vendor.state

        if vendor_invoice_no:
            duplicate = PurchaseInvoice.query.filter(
                PurchaseInvoice.company_id == company_id,
                PurchaseInvoice.vendor_id == vendor.id,
                PurchaseInvoice.vendor_invoice_no == vendor_invoice_no,
                PurchaseInvoice.is_deleted.is_(False),
            ).first()

            if duplicate:
                flash("Duplicate vendor invoice number already exists for this vendor.", "danger")
                return redirect(url_for("purchase.add_invoice"))

        duplicate_bill_no = PurchaseInvoice.query.filter(
            PurchaseInvoice.company_id == company_id,
            PurchaseInvoice.bill_no == bill_no,
            PurchaseInvoice.is_deleted.is_(False),
        ).first()

        if duplicate_bill_no:
            flash("Internal bill number already exists.", "danger")
            return redirect(url_for("purchase.add_invoice"))

        expense_ledger_ids = request.form.getlist("expense_ledger_id[]")
        descriptions = request.form.getlist("description[]")
        qtys = request.form.getlist("qty[]")
        rates = request.form.getlist("rate[]")
        discounts = request.form.getlist("discount_amount[]")
        hsn_sacs = request.form.getlist("hsn_sac[]")
        gst_rates = request.form.getlist("gst_rate[]")

        gst_service = GSTService(company_id)

        items = []
        subtotal = Decimal("0.00")
        total_discount = Decimal("0.00")
        total_cgst = Decimal("0.00")
        total_sgst = Decimal("0.00")
        total_igst = Decimal("0.00")

        for i, desc in enumerate(descriptions):
            if not desc:
                continue

            expense_ledger_id = int(expense_ledger_ids[i]) if i < len(expense_ledger_ids) and expense_ledger_ids[i] else None
            qty = money(qtys[i] if i < len(qtys) else 0)
            rate = money(rates[i] if i < len(rates) else 0)
            discount = money(discounts[i] if i < len(discounts) else 0)
            gst_rate = money(gst_rates[i] if i < len(gst_rates) else 0)
            hsn_sac = hsn_sacs[i] if i < len(hsn_sacs) else None

            if not expense_ledger_id or qty <= 0 or rate <= 0:
                continue

            gross = qty * rate
            taxable = gross - discount

            if gst_type in ["exempt", "non_gst", "pure_agent"]:
                cgst_amount = Decimal("0.00")
                sgst_amount = Decimal("0.00")
                igst_amount = Decimal("0.00")
                total_tax = Decimal("0.00")
                gst_rate = Decimal("0.00")

            elif gst_type == "igst":
                igst_amount = (taxable * gst_rate / Decimal("100.00")).quantize(Decimal("0.01"))
                cgst_amount = Decimal("0.00")
                sgst_amount = Decimal("0.00")
                total_tax = igst_amount

            else:
                gst = gst_service.calculate_line_gst(taxable, gst_rate, vendor_state_for_gst)
                cgst_amount = gst["cgst_amount"]
                sgst_amount = gst["sgst_amount"]
                igst_amount = gst["igst_amount"]
                total_tax = gst["total_tax"]

            line_total = taxable + total_tax

            subtotal += gross
            total_discount += discount
            total_cgst += cgst_amount
            total_sgst += sgst_amount
            total_igst += igst_amount

            items.append(
                {
                    "expense_ledger_id": expense_ledger_id,
                    "description": desc,
                    "hsn_sac": hsn_sac,
                    "qty": qty,
                    "rate": rate,
                    "discount_amount": discount,
                    "gst_rate": gst_rate,
                    "gst_type": gst_type,
                    "taxable_amount": taxable,
                    "cgst_amount": cgst_amount,
                    "sgst_amount": sgst_amount,
                    "igst_amount": igst_amount,
                    "line_total": line_total,
                }
            )

        if not items:
            flash("Please add at least one valid purchase line.", "danger")
            return redirect(url_for("purchase.add_invoice"))

        tax_amount = total_cgst + total_sgst + total_igst
        round_off_amount = money(request.form.get("round_off_amount") or 0)
        taxable_total = subtotal - total_discount
        total_amount = taxable_total + tax_amount + round_off_amount

        tds_amount = Decimal("0.00")

        if tds_applicable:
            if not tds_section_id:
                flash("Please select TDS section.", "danger")
                return redirect(url_for("purchase.add_invoice"))

            tds_amount = (taxable_total * tds_rate / Decimal("100.00")).quantize(Decimal("0.01"))

        net_payable_amount = total_amount - tds_amount

        try:
            attachment_path = None
            try:
                attachment_path = save_purchase_attachment(
                    request.files.get("bill_attachment"),
                    bill_no,
                )
            except ValueError as exc:
                flash(str(exc), "danger")
                return redirect(url_for("purchase.add_invoice"))

            voucher = None

            if not is_draft:
                entries = build_purchase_posting_entries(
                    company_id=company_id,
                    vendor=vendor,
                    bill_no=bill_no,
                    items=items,
                    total_cgst=total_cgst,
                    total_sgst=total_sgst,
                    total_igst=total_igst,
                    round_off_amount=round_off_amount,
                    total_amount=total_amount,
                    gst_type=gst_type,
                    tds_amount=tds_amount,
                )

                engine = PostingEngine(company_id=company_id, user_id=session.get("user_id"))
                voucher = engine.create_voucher(
                    voucher_date=posting_date,
                    type_code="PI",
                    entries=entries,
                    reference_no=reference_no or vendor_invoice_no,
                    narration=narration or f"Purchase bill {bill_no}",
                    source_module="purchase",
                    source_doc_type="purchase_invoice",
                    external_ref_no=f"PURCHASE-{bill_no}",
                    auto_approve=True,
                    auto_post=True,
                )

            invoice = PurchaseInvoice(
                company_id=company_id,
                vendor_id=vendor.id,
                vendor_gstin_id=vendor_gstin_row.id if vendor_gstin_row else None,
                vendor_gstin=vendor_gstin_row.gstin if vendor_gstin_row else vendor.gstin,
                voucher_id=voucher.id if voucher else None,
                bill_no=bill_no,
                entry_date=entry_date,
                posting_date=posting_date,
                bill_date=bill_date,
                vendor_invoice_no=vendor_invoice_no,
                reference_no=reference_no,
                subtotal=subtotal,
                discount_amount=total_discount,
                tax_amount=tax_amount,
                round_off_amount=round_off_amount,
                total_amount=total_amount,
                status="draft" if is_draft else "posted",
                is_draft=is_draft,
                gst_type=gst_type,
                currency_code=currency_code,
                exchange_rate=exchange_rate,
                attachment_path=attachment_path,
                narration=narration,
                tds_applicable=tds_applicable,
                tds_section_id=tds_section_id if tds_applicable else None,
                tds_rate=tds_rate if tds_applicable else 0,
                tds_amount=tds_amount,
                net_payable_amount=net_payable_amount,
            )
            db.session.add(invoice)
            db.session.flush()

            for item in items:
                db.session.add(
                    PurchaseInvoiceItem(
                        purchase_invoice_id=invoice.id,
                        expense_ledger_id=item["expense_ledger_id"],
                        description=item["description"],
                        hsn_sac=item["hsn_sac"],
                        qty=item["qty"],
                        rate=item["rate"],
                        discount_amount=item["discount_amount"],
                        gst_rate=item["gst_rate"],
                        gst_type=item["gst_type"],
                        taxable_amount=item["taxable_amount"],
                        cgst_amount=item["cgst_amount"],
                        sgst_amount=item["sgst_amount"],
                        igst_amount=item["igst_amount"],
                        line_total=item["line_total"],
                    )
                )

            if voucher:
                voucher.source_doc_id = invoice.id

            db.session.commit()

            if is_draft:
                flash(f"Purchase bill {invoice.bill_no} saved as draft because posting date is future.", "warning")
            else:
                flash(f"Purchase bill {invoice.bill_no} posted successfully.", "success")

            return redirect(url_for("purchase.invoice_detail", invoice_id=invoice.id))

        except (PostingError, ValueError) as exc:
            db.session.rollback()
            flash(str(exc), "danger")

    return render_template(
        "purchase/invoice_form.html",
        vendors=vendors,
        expense_ledgers=expense_ledgers,
        hsn_codes=hsn_codes,
        today=date.today().isoformat(),
        bill_no=next_purchase_bill_no(company_id),
        copy_invoice=None,
        tds_sections=tds_sections,
        vendor_gstins=VendorGSTIN.query.filter_by(company_id=company_id, active=True).all(),
    )


@purchase_bp.route("/invoices/<int:invoice_id>")
@login_required
@permission_required("accounts.view")
def invoice_detail(invoice_id):
    company_id = current_company_id()
    invoice = PurchaseInvoice.query.filter_by(
        id=invoice_id,
        company_id=company_id,
        is_deleted=False,
    ).first_or_404()
    return render_template("purchase/invoice_detail.html", invoice=invoice)


@purchase_bp.route("/invoices/<int:invoice_id>/copy")
@login_required
@permission_required("vouchers.create")
def copy_invoice(invoice_id):
    company_id = current_company_id()

    source_invoice = PurchaseInvoice.query.filter_by(
        id=invoice_id,
        company_id=company_id,
        is_deleted=False,
    ).first_or_404()

    vendors, expense_ledgers, hsn_codes, tds_sections = get_purchase_form_data(company_id)

    return render_template(
        "purchase/invoice_form.html",
        vendors=vendors,
        expense_ledgers=expense_ledgers,
        hsn_codes=hsn_codes,
        today=date.today().isoformat(),
        bill_no=next_purchase_bill_no(company_id),
        copy_invoice=source_invoice,
        tds_sections=tds_sections,
        vendor_gstins=VendorGSTIN.query.filter_by(company_id=company_id, active=True).all(),
    )

@purchase_bp.route("/invoices/<int:invoice_id>/post-draft", methods=["POST"])
@login_required
@permission_required("vouchers.create")
def post_draft_invoice(invoice_id):
    company_id = current_company_id()

    invoice = PurchaseInvoice.query.filter_by(
        id=invoice_id,
        company_id=company_id,
        is_deleted=False,
    ).first_or_404()

    if invoice.status != "draft" or not invoice.is_draft:
        flash("Only draft purchase bills can be posted.", "warning")
        return redirect(url_for("purchase.invoice_detail", invoice_id=invoice.id))

    if invoice.posting_date > date.today():
        flash("Future dated bill cannot be posted before posting date.", "danger")
        return redirect(url_for("purchase.invoice_detail", invoice_id=invoice.id))

    if invoice.voucher_id:
        flash("This purchase bill is already linked to a voucher.", "warning")
        return redirect(url_for("purchase.invoice_detail", invoice_id=invoice.id))

    try:
        items = []
        total_cgst = Decimal("0.00")
        total_sgst = Decimal("0.00")
        total_igst = Decimal("0.00")

        for item in invoice.items:
            items.append({
                "expense_ledger_id": item.expense_ledger_id,
                "taxable_amount": money(item.taxable_amount),
            })
            total_cgst += money(item.cgst_amount)
            total_sgst += money(item.sgst_amount)
            total_igst += money(item.igst_amount)

        entries = build_purchase_posting_entries(
            company_id=company_id,
            vendor=invoice.vendor,
            bill_no=invoice.bill_no,
            items=items,
            total_cgst=total_cgst,
            total_sgst=total_sgst,
            total_igst=total_igst,
            round_off_amount=money(invoice.round_off_amount),
            total_amount=money(invoice.total_amount),
            gst_type=invoice.gst_type,
            tds_amount=money(invoice.tds_amount),
        )

        engine = PostingEngine(company_id=company_id, user_id=session.get("user_id"))
        voucher = engine.create_voucher(
            voucher_date=invoice.posting_date,
            type_code="PI",
            entries=entries,
            reference_no=invoice.reference_no or invoice.vendor_invoice_no,
            narration=invoice.narration or f"Purchase bill {invoice.bill_no}",
            source_module="purchase",
            source_doc_type="purchase_invoice",
            source_doc_id=invoice.id,
            external_ref_no=f"PURCHASE-{invoice.bill_no}",
            auto_approve=True,
            auto_post=True,
        )

        invoice.voucher_id = voucher.id
        invoice.status = "posted"
        invoice.is_draft = False

        db.session.commit()

        flash(f"Draft purchase bill {invoice.bill_no} posted successfully.", "success")
        return redirect(url_for("purchase.invoice_detail", invoice_id=invoice.id))

    except (PostingError, ValueError) as exc:
        db.session.rollback()
        flash(str(exc), "danger")
        return redirect(url_for("purchase.invoice_detail", invoice_id=invoice.id))
    
def ensure_debit_note_voucher_type(company_id):
    vt = VoucherType.query.filter_by(
        company_id=company_id,
        type_code="DN",
        is_deleted=False,
    ).first()

    if vt:
        return vt

    vt = VoucherType(
        company_id=company_id,
        type_code="DN",
        type_name="Debit Note",
        numbering_method="auto",
        prefix="DN-",
        current_number=0,
        requires_approval=False,
        active=True,
    )
    db.session.add(vt)
    db.session.flush()
    return vt


def build_purchase_debit_note_entries(company_id, invoice):
    gst_service = GSTService(company_id)

    entries = []
    ledger_totals = {}

    for item in invoice.items:
        ledger_totals[item.expense_ledger_id] = (
            ledger_totals.get(item.expense_ledger_id, Decimal("0.00"))
            + money(item.taxable_amount)
        )

    round_off = money(invoice.round_off_amount or 0)
    first_expense_done = False

    for ledger_id, amount in ledger_totals.items():
        credit_amount = money(amount)
        if not first_expense_done:
            credit_amount += round_off
            first_expense_done = True

        if credit_amount > 0:
            entries.append({
                "ledger_id": ledger_id,
                "debit_amount": 0,
                "credit_amount": credit_amount,
                "line_narration": f"Debit note against {invoice.bill_no}",
            })

    total_cgst = sum(money(item.cgst_amount) for item in invoice.items)
    total_sgst = sum(money(item.sgst_amount) for item in invoice.items)
    total_igst = sum(money(item.igst_amount) for item in invoice.items)

    if total_cgst > 0:
        entries.append({
            "ledger_id": gst_service.input_cgst_ledger().id,
            "debit_amount": 0,
            "credit_amount": total_cgst,
            "line_narration": f"Input CGST reversed against {invoice.bill_no}",
        })

    if total_sgst > 0:
        entries.append({
            "ledger_id": gst_service.input_sgst_ledger().id,
            "debit_amount": 0,
            "credit_amount": total_sgst,
            "line_narration": f"Input SGST reversed against {invoice.bill_no}",
        })

    if total_igst > 0:
        entries.append({
            "ledger_id": gst_service.input_igst_ledger().id,
            "debit_amount": 0,
            "credit_amount": total_igst,
            "line_narration": f"Input IGST reversed against {invoice.bill_no}",
        })

    if invoice.gst_type == "rcm":
        if total_cgst > 0:
            entries.append({
                "ledger_id": get_or_create_tax_ledger(company_id, "RCM CGST Payable", "RCM-CGST").id,
                "debit_amount": total_cgst,
                "credit_amount": 0,
                "line_narration": f"RCM CGST reversed against {invoice.bill_no}",
            })
        if total_sgst > 0:
            entries.append({
                "ledger_id": get_or_create_tax_ledger(company_id, "RCM SGST Payable", "RCM-SGST").id,
                "debit_amount": total_sgst,
                "credit_amount": 0,
                "line_narration": f"RCM SGST reversed against {invoice.bill_no}",
            })
        if total_igst > 0:
            entries.append({
                "ledger_id": get_or_create_tax_ledger(company_id, "RCM IGST Payable", "RCM-IGST").id,
                "debit_amount": total_igst,
                "credit_amount": 0,
                "line_narration": f"RCM IGST reversed against {invoice.bill_no}",
            })

    if money(invoice.tds_amount or 0) > 0:
        entries.append({
            "ledger_id": get_or_create_tds_payable_ledger(company_id).id,
            "debit_amount": money(invoice.tds_amount),
            "credit_amount": 0,
            "line_narration": f"TDS reversed against {invoice.bill_no}",
        })

    vendor_debit = money(invoice.net_payable_amount or invoice.total_amount)

    entries.insert(0, {
        "ledger_id": invoice.vendor.ledger_id,
        "debit_amount": vendor_debit,
        "credit_amount": 0,
        "line_narration": f"Debit note against {invoice.bill_no}",
        "party_type": "vendor",
        "party_id": invoice.vendor_id,
        "bill_ref_no": invoice.bill_no,
        "bill_ref_type": "purchase_debit_note",
    })

    return entries
    
@purchase_bp.route("/invoices/<int:invoice_id>/reverse", methods=["POST"])
@login_required
@permission_required("vouchers.create")
def reverse_invoice(invoice_id):
    company_id = current_company_id()

    invoice = PurchaseInvoice.query.filter_by(
        id=invoice_id,
        company_id=company_id,
        is_deleted=False,
    ).first_or_404()

    if invoice.status != "posted" or not invoice.voucher_id:
        flash("Only posted purchase bills can be reversed.", "warning")
        return redirect(url_for("purchase.invoice_detail", invoice_id=invoice.id))

    try:
        engine = PostingEngine(company_id=company_id, user_id=session.get("user_id"))

        reversal = engine.reverse_voucher(
            voucher_id=invoice.voucher_id,
            reversal_date=date.today(),
            narration=f"Reversal of purchase bill {invoice.bill_no}",
        )

        invoice.status = "reversed"
        invoice.is_draft = False

        db.session.commit()

        flash(f"Purchase bill {invoice.bill_no} reversed successfully.", "success")
        return redirect(url_for("vouchers.voucher_detail", voucher_id=reversal.id))

    except (PostingError, ValueError) as exc:
        db.session.rollback()
        flash(str(exc), "danger")
        return redirect(url_for("purchase.invoice_detail", invoice_id=invoice.id))
    
@purchase_bp.route("/invoices/<int:invoice_id>/debit-note", methods=["POST"])
@login_required
@permission_required("vouchers.create")
def create_debit_note(invoice_id):
    company_id = current_company_id()

    invoice = PurchaseInvoice.query.filter_by(
        id=invoice_id,
        company_id=company_id,
        is_deleted=False,
    ).first_or_404()

    if invoice.status != "posted" or not invoice.voucher_id:
        flash("Debit note can be created only for posted purchase bills.", "warning")
        return redirect(url_for("purchase.invoice_detail", invoice_id=invoice.id))

    existing_dn = VoucherType.query.join(
        # harmless placeholder not used; remove if your editor complains
        VoucherType.company
    ) if False else None

    already_exists = (
        PurchasePaymentAllocation.query.join(
            PurchasePaymentAllocation.voucher
        )
        .filter(
            PurchasePaymentAllocation.company_id == company_id,
            PurchasePaymentAllocation.purchase_invoice_id == invoice.id,
            Voucher.source_module == "purchase",
            Voucher.source_doc_type == "purchase_debit_note",
            Voucher.is_deleted.is_(False),
        )
        .first()
    )

    if already_exists:
        flash("Debit note already exists for this purchase bill.", "warning")
        return redirect(url_for("purchase.invoice_detail", invoice_id=invoice.id))

    try:
        ensure_debit_note_voucher_type(company_id)

        entries = build_purchase_debit_note_entries(company_id, invoice)

        engine = PostingEngine(company_id=company_id, user_id=session.get("user_id"))
        voucher = engine.create_voucher(
            voucher_date=date.today(),
            type_code="DN",
            entries=entries,
            reference_no=f"DN-{invoice.bill_no}",
            narration=f"Debit note against purchase bill {invoice.bill_no}",
            source_module="purchase",
            source_doc_type="purchase_debit_note",
            source_doc_id=invoice.id,
            external_ref_no=f"PURCHASE-DN-{invoice.bill_no}",
            auto_approve=True,
            auto_post=True,
        )

        db.session.add(PurchasePaymentAllocation(
            company_id=company_id,
            vendor_id=invoice.vendor_id,
            purchase_invoice_id=invoice.id,
            voucher_id=voucher.id,
            allocated_amount=money(invoice.net_payable_amount or invoice.total_amount),
        ))

        invoice.status = "debit_note"

        db.session.commit()

        flash(f"Debit note created against purchase bill {invoice.bill_no}.", "success")
        return redirect(url_for("vouchers.voucher_detail", voucher_id=voucher.id))

    except (PostingError, ValueError) as exc:
        db.session.rollback()
        flash(str(exc), "danger")
        return redirect(url_for("purchase.invoice_detail", invoice_id=invoice.id))