import os
from collections import defaultdict
from datetime import date, datetime, timedelta
from decimal import Decimal, ROUND_HALF_UP
from io import BytesIO

from flask import abort, current_app, flash, redirect, render_template, request, send_file, url_for
from flask_login import current_user, login_required
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font
from openpyxl.utils import get_column_letter
from sqlalchemy import and_, func, or_

from app import db
from app.audit import log_audit
from app.models import (
    Invoice, InvoicePayment, OperationsJobcard, OperationsJobcardAssignment,
    OperationsJobcardService, VendorInvoice, VendorInvoiceItem, VendorInvoicePayment,
    VendorInvoicePaymentAllocation, VendorMaster,
)
from app.utils import require_perm
from app.services.tally_service import TallyService
from . import vendor_finance_bp
from .invoice_pdf import generate_system_vendor_invoice_pdf

PAYMENT_STATUSES = ("Pending", "Scheduled", "Partially Paid", "Paid", "On Hold", "Rejected")


def _tds_values(invoice):
    is_inr = (invoice.currency or "").strip().upper() == "INR"
    tds_base = invoice.calculated_taxable_amount if invoice.gst_registered else None
    rate, tds, net = VendorInvoice.calculate_tds_values(invoice.total_amount, invoice.currency, tds_base)
    return is_inr, rate, tds, net


def _item_net_shares(invoice):
    """Allocate invoice net payable across invoice items, preserving the invoice total exactly."""
    items = list(invoice.items or [])
    if not items:
        return {}
    net_total = Decimal(str(invoice.calculated_net_payable_amount or 0)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    taxable_total = sum((Decimal(str(i.amount or 0)) for i in items), Decimal("0.00"))
    shares = {}
    running = Decimal("0.00")
    for pos, item in enumerate(items):
        if pos == len(items) - 1:
            share = net_total - running
        elif taxable_total:
            share = (net_total * Decimal(str(item.amount or 0)) / taxable_total).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            running += share
        else:
            share = Decimal("0.00")
        shares[item.id] = share.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    return shares


def _transaction_allocated_by_item(invoice, status):
    """Return allocation totals for an invoice/payment status from the DB.

    Do not calculate this from already-loaded relationship collections. During a
    payment update SQLAlchemy can have a stale ``payment.allocations`` collection
    in memory (for example immediately after a Scheduled transaction is created,
    or while it is being changed to Paid). A grouped query triggers autoflush and
    therefore always sees the latest transaction/allocation state before the
    invoice-level payment status is recalculated.
    """
    totals = defaultdict(lambda: Decimal("0.00"))
    rows = (
        db.session.query(
            VendorInvoicePaymentAllocation.vendor_invoice_item_id,
            func.coalesce(func.sum(VendorInvoicePaymentAllocation.allocated_amount), 0),
        )
        .join(
            VendorInvoicePayment,
            VendorInvoicePayment.id == VendorInvoicePaymentAllocation.payment_id,
        )
        .filter(
            VendorInvoicePayment.vendor_invoice_id == invoice.id,
            VendorInvoicePayment.status == status,
        )
        .group_by(VendorInvoicePaymentAllocation.vendor_invoice_item_id)
        .all()
    )
    for item_id, allocated_amount in rows:
        totals[item_id] = Decimal(str(allocated_amount or 0)).quantize(Decimal("0.01"))
    return totals


def _jobcard_payment_rows(invoice):
    shares = _item_net_shares(invoice)
    paid_by_item = _transaction_allocated_by_item(invoice, "Paid")
    scheduled_by_item = _transaction_allocated_by_item(invoice, "Scheduled")
    historical_paid = not getattr(invoice, "payment_transactions", None) and invoice.payment_status == "Paid"
    historical_scheduled = not getattr(invoice, "payment_transactions", None) and invoice.payment_status == "Scheduled"
    grouped = {}
    for item in invoice.items or []:
        key = item.jobcard_id or item.jobcard_code or item.id
        row = grouped.setdefault(key, {
            "key": str(key), "jobcard_id": item.jobcard_id, "jobcard_code": item.jobcard_code or "—",
            "services": [], "item_ids": [], "taxable": Decimal("0.00"), "net": Decimal("0.00"),
            "paid": Decimal("0.00"), "scheduled": Decimal("0.00"), "remaining": Decimal("0.00"),
        })
        if item.service_name and item.service_name not in row["services"]:
            row["services"].append(item.service_name)
        row["item_ids"].append(item.id)
        row["taxable"] += Decimal(str(item.amount or 0))
        share = shares.get(item.id, Decimal("0.00"))
        row["net"] += share
        paid = share if historical_paid else min(share, paid_by_item.get(item.id, Decimal("0.00")))
        row["paid"] += paid
        sched_cap = max(Decimal("0.00"), share - paid)
        scheduled = sched_cap if historical_scheduled else min(sched_cap, scheduled_by_item.get(item.id, Decimal("0.00")))
        row["scheduled"] += scheduled
    for row in grouped.values():
        row["remaining"] = max(Decimal("0.00"), row["net"] - row["paid"]).quantize(Decimal("0.01"))
        for k in ("taxable", "net", "paid", "scheduled"):
            row[k] = Decimal(str(row[k])).quantize(Decimal("0.01"))
        row["service_display"] = ", ".join(row["services"])
    return list(grouped.values())


def _invoice_progress(invoice):
    rows = _jobcard_payment_rows(invoice)
    paid = sum((r["paid"] for r in rows), Decimal("0.00"))
    remaining = max(Decimal("0.00"), Decimal(str(invoice.calculated_net_payable_amount or 0)) - paid)
    scheduled = sum((min(r["scheduled"], r["remaining"]) for r in rows), Decimal("0.00"))
    return {
        "paid": paid.quantize(Decimal("0.01")),
        "scheduled": scheduled.quantize(Decimal("0.01")),
        "remaining": remaining.quantize(Decimal("0.01")),
        "net": Decimal(str(invoice.calculated_net_payable_amount or 0)).quantize(Decimal("0.01")),
    }


def _refresh_invoice_payment_status(invoice):
    progress = _invoice_progress(invoice)
    tolerance = Decimal("0.01")
    if progress["remaining"] <= tolerance and progress["net"] > 0:
        invoice.payment_status = "Paid"
        invoice.status = "PAID"
        paid_tx = [p for p in invoice.payment_transactions if p.status == "Paid"]
        if paid_tx:
            latest = max(paid_tx, key=lambda p: (p.payment_date or date.min, p.id or 0))
            invoice.payment_date = latest.payment_date
            invoice.payment_reference = latest.reference
    elif progress["paid"] > 0:
        invoice.payment_status = "Partially Paid"
        invoice.status = "RAISED"
        paid_tx = [p for p in invoice.payment_transactions if p.status == "Paid"]
        if paid_tx:
            latest = max(paid_tx, key=lambda p: (p.payment_date or date.min, p.id or 0))
            invoice.payment_date = latest.payment_date
            invoice.payment_reference = latest.reference
    elif progress["scheduled"] > 0:
        invoice.payment_status = "Scheduled"
        invoice.status = "RAISED"
        sched_tx = [p for p in invoice.payment_transactions if p.status == "Scheduled"]
        if sched_tx:
            latest = max(sched_tx, key=lambda p: (p.payment_date or date.min, p.id or 0))
            invoice.payment_date = latest.payment_date
            invoice.payment_reference = latest.reference
    else:
        invoice.payment_status = "Pending"
        invoice.status = "RAISED"
    invoice.payment_updated_at = datetime.utcnow()
    invoice.payment_updated_by_id = current_user.id
    return progress


def _record_jobcard_payment(invoice, status, payment_date, selected_keys, reference=None, remarks=None):
    if status not in ("Paid", "Scheduled"):
        raise ValueError("Payment transaction must be Paid or Scheduled.")
    rows = _jobcard_payment_rows(invoice)
    chosen = [r for r in rows if r["key"] in selected_keys and r["remaining"] > 0]
    if not chosen:
        raise ValueError("Select at least one unpaid jobcard.")
    all_remaining_keys = {r["key"] for r in rows if r["remaining"] > 0}
    mode = "FULL" if {r["key"] for r in chosen} == all_remaining_keys else "PARTIAL"
    tx = VendorInvoicePayment(
        vendor_invoice_id=invoice.id, status=status, payment_mode=mode,
        payment_date=payment_date, currency=invoice.currency,
        reference=reference, remarks=remarks, created_by_id=current_user.id,
    )
    db.session.add(tx)
    db.session.flush()
    shares = _item_net_shares(invoice)
    paid_by_item = _transaction_allocated_by_item(invoice, "Paid")
    amount = Decimal("0.00")
    chosen_item_ids = {iid for r in chosen for iid in r["item_ids"]}
    for item in invoice.items or []:
        if item.id not in chosen_item_ids:
            continue
        share = shares.get(item.id, Decimal("0.00"))
        paid_already = min(share, paid_by_item.get(item.id, Decimal("0.00")))
        alloc_amount = max(Decimal("0.00"), share - paid_already).quantize(Decimal("0.01"))
        if alloc_amount <= 0:
            continue
        db.session.add(VendorInvoicePaymentAllocation(
            payment_id=tx.id, vendor_invoice_item_id=item.id, allocated_amount=alloc_amount
        ))
        amount += alloc_amount
    if amount <= 0:
        raise ValueError("The selected jobcards are already fully paid.")
    tx.amount = amount.quantize(Decimal("0.01"))
    return tx


def _sync_tds(invoice, confirmed=False):
    is_inr, rate, tds, net = _tds_values(invoice)
    invoice.tds_rate = rate
    invoice.tds_amount = tds
    invoice.net_payable_amount = net
    if confirmed and is_inr:
        invoice.tds_confirmed = True
        invoice.tds_confirmed_at = datetime.utcnow()
        invoice.tds_confirmed_by_id = current_user.id
    elif not is_inr:
        invoice.tds_confirmed = False
        invoice.tds_confirmed_at = None
        invoice.tds_confirmed_by_id = None
    return is_inr, rate, tds, net


def _safe_static_file(relative_path):
    relative_path = (relative_path or "").strip().replace("\\", "/")
    if not relative_path: return None
    static_root = os.path.abspath(os.path.join(current_app.root_path, "static"))
    full_path = os.path.abspath(os.path.join(static_root, relative_path))
    if full_path != static_root and not full_path.startswith(static_root + os.sep): abort(403)
    if not os.path.isfile(full_path): return None
    return full_path


def _invoice_query():
    q = (request.args.get("q") or "").strip()
    payment_status = (request.args.get("payment_status") or "").strip()
    currency = (request.args.get("currency") or "").strip()
    date_from = (request.args.get("date_from") or "").strip()
    date_to = (request.args.get("date_to") or "").strip()
    query = VendorInvoice.query.join(VendorMaster, VendorMaster.id == VendorInvoice.vendor_id)
    if q:
        like = f"%{q}%"
        query = query.filter(or_(VendorInvoice.vendor_invoice_no.ilike(like), VendorMaster.name.ilike(like), VendorMaster.external_translator_id.ilike(like), VendorInvoice.payment_reference.ilike(like)))
    if payment_status: query = query.filter(VendorInvoice.payment_status == payment_status)
    if currency: query = query.filter(func.upper(VendorInvoice.currency) == currency.upper())
    if date_from:
        try: query = query.filter(VendorInvoice.invoice_date >= datetime.strptime(date_from, "%Y-%m-%d").date())
        except ValueError: pass
    if date_to:
        try: query = query.filter(VendorInvoice.invoice_date <= datetime.strptime(date_to, "%Y-%m-%d").date())
        except ValueError: pass
    return query, {"q":q,"payment_status":payment_status,"currency":currency,"date_from":date_from,"date_to":date_to}


def _currency_totals(invoices):
    totals = defaultdict(lambda: {
        "raised": Decimal("0"), "gst": Decimal("0"), "tds": Decimal("0"),
        "net": Decimal("0"), "due": Decimal("0"), "due_gross": Decimal("0"),
        "paid": Decimal("0"), "paid_gross": Decimal("0"), "overdue": Decimal("0"),
        "overdue_gross": Decimal("0"), "scheduled": Decimal("0"), "count": 0,
    })
    today = date.today()
    for inv in invoices:
        cur = inv.currency or "—"
        gross = Decimal(str(inv.total_amount or 0)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        _, _, tds, net = _tds_values(inv)
        progress = _invoice_progress(inv)
        t = totals[cur]
        t["raised"] += gross; t["gst"] += inv.calculated_gst_amount; t["tds"] += tds; t["net"] += net; t["count"] += 1
        if inv.payment_status == "Rejected":
            continue
        t["paid"] += progress["paid"]
        t["scheduled"] += progress["scheduled"]
        t["due"] += progress["remaining"]
        if net > 0:
            paid_ratio = min(Decimal("1"), progress["paid"] / net)
            t["paid_gross"] += (gross * paid_ratio).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            t["due_gross"] += (gross * (Decimal("1") - paid_ratio)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        if progress["remaining"] > 0 and inv.due_date and inv.due_date < today:
            t["overdue"] += progress["remaining"]
            if net > 0:
                t["overdue_gross"] += (gross * (progress["remaining"] / net)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    return dict(sorted(totals.items()))


@vendor_finance_bp.route("/summary")
@login_required
@require_perm("vendor_invoice.view")
def summary():
    all_invoices = (
        VendorInvoice.query
        .join(VendorMaster)
        .order_by(VendorMaster.name.asc(), VendorInvoice.invoice_date.desc())
        .all()
    )

    def branch_name(inv):
        name = (inv.bill_to_branch_name or "").strip()
        if name:
            return name
        names = inv.invoice_branch_names
        if len(names) == 1:
            return names[0]
        if len(names) > 1:
            return "Multiple: " + ", ".join(names)
        return "Unassigned"

    branch_options = sorted({branch_name(inv) for inv in all_invoices}, key=lambda x: x.lower())
    currency_options = sorted({(inv.currency or "—").strip().upper() for inv in all_invoices})

    selected_branch = (request.args.get("branch") or "").strip()
    selected_currency = (request.args.get("currency") or "").strip().upper()

    invoices = [
        inv for inv in all_invoices
        if (not selected_branch or branch_name(inv) == selected_branch)
        and (not selected_currency or (inv.currency or "—").strip().upper() == selected_currency)
    ]

    today = date.today()
    due_statuses = {"Pending", "Scheduled", "Partially Paid", "On Hold"}
    groups = {}
    branch_currency = {}

    generated_count = 0
    paid_count = 0
    due_count = 0
    overdue_count = 0
    scheduled_count = 0
    on_hold_count = 0
    rejected_count = 0
    upcoming_7_count = 0
    active_vendors = set()
    active_branches = set()
    active_currencies = set()

    ageing = defaultdict(lambda: {
        "current": Decimal("0"),
        "days_1_30": Decimal("0"),
        "days_31_60": Decimal("0"),
        "days_61_90": Decimal("0"),
        "days_90_plus": Decimal("0"),
    })

    for inv in invoices:
        gross = Decimal(str(inv.total_amount or 0)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        taxable = Decimal(str(inv.calculated_taxable_amount or 0)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        gst = Decimal(str(inv.calculated_gst_amount or 0)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        _, _, tds, net = _tds_values(inv)
        cur = (inv.currency or "—").strip().upper()
        branch = branch_name(inv)

        active_vendors.add(inv.vendor_id)
        active_branches.add(branch)
        active_currencies.add(cur)

        # Vendor + currency position
        key = (inv.vendor_id, cur)
        if key not in groups:
            groups[key] = {
                "vendor": inv.vendor,
                "currency": cur,
                "invoice_count": 0,
                "generated_count": 0,
                "uploaded_count": 0,
                "raised": Decimal("0"),
                "gst": Decimal("0"),
                "tds": Decimal("0"),
                "net_payable": Decimal("0"),
                "due": Decimal("0"),
                "due_gross": Decimal("0"),
                "paid": Decimal("0"),
                "paid_gross": Decimal("0"),
                "overdue": Decimal("0"),
                "overdue_gross": Decimal("0"),
                "scheduled": Decimal("0"),
                "on_hold": Decimal("0"),
                "rejected": Decimal("0"),
                "next_due": None,
                "last_invoice_date": None,
                "last_payment_date": None,
            }

        row = groups[key]
        row["invoice_count"] += 1
        row["raised"] += gross
        row["gst"] += gst
        row["tds"] += tds
        row["net_payable"] += net

        # Crystal Hues branch + currency position
        bkey = (branch, cur)
        if bkey not in branch_currency:
            branch_currency[bkey] = {
                "branch": branch,
                "currency": cur,
                "invoice_count": 0,
                "vendor_ids": set(),
                "taxable": Decimal("0"),
                "gst": Decimal("0"),
                "raised": Decimal("0"),
                "tds": Decimal("0"),
                "net_payable": Decimal("0"),
                "due": Decimal("0"),
                "paid": Decimal("0"),
                "overdue": Decimal("0"),
                "pending_count": 0,
                "paid_count": 0,
                "overdue_count": 0,
                "next_due": None,
            }
        brow = branch_currency[bkey]
        brow["invoice_count"] += 1
        brow["vendor_ids"].add(inv.vendor_id)
        brow["taxable"] += taxable
        brow["gst"] += gst
        brow["raised"] += gross
        brow["tds"] += tds
        brow["net_payable"] += net

        if inv.invoice_source == "GENERATED":
            row["generated_count"] += 1
            generated_count += 1
        else:
            row["uploaded_count"] += 1

        if not row["last_invoice_date"] or inv.invoice_date > row["last_invoice_date"]:
            row["last_invoice_date"] = inv.invoice_date

        progress = _invoice_progress(inv)
        paid_amt = progress["paid"]
        remaining_amt = progress["remaining"]
        scheduled_amt = progress["scheduled"]
        gross_paid = (gross * (paid_amt / net)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if net else Decimal("0.00")
        gross_due = max(Decimal("0.00"), gross - gross_paid)

        row["paid_gross"] += gross_paid
        row["paid"] += paid_amt
        row["due_gross"] += gross_due if inv.payment_status != "Rejected" else Decimal("0.00")
        row["due"] += remaining_amt if inv.payment_status != "Rejected" else Decimal("0.00")
        brow["paid"] += paid_amt
        brow["due"] += remaining_amt if inv.payment_status != "Rejected" else Decimal("0.00")

        if inv.payment_status == "Paid":
            brow["paid_count"] += 1
            paid_count += 1
        elif inv.payment_status in due_statuses:
            brow["pending_count"] += 1
            due_count += 1
            if scheduled_amt > 0 or inv.payment_status == "Scheduled":
                row["scheduled"] += scheduled_amt if scheduled_amt > 0 else remaining_amt
                scheduled_count += 1
            if inv.payment_status == "On Hold":
                row["on_hold"] += remaining_amt
                on_hold_count += 1

        if paid_amt > 0 and inv.payment_date and (
            not row["last_payment_date"] or inv.payment_date > row["last_payment_date"]
        ):
            row["last_payment_date"] = inv.payment_date

        if remaining_amt > 0 and inv.payment_status != "Rejected" and inv.due_date:
            if row["next_due"] is None or inv.due_date < row["next_due"]:
                row["next_due"] = inv.due_date
            if brow["next_due"] is None or inv.due_date < brow["next_due"]:
                brow["next_due"] = inv.due_date
            if today <= inv.due_date <= today + timedelta(days=7):
                upcoming_7_count += 1
            if inv.due_date < today:
                row["overdue_gross"] += gross_due
                row["overdue"] += remaining_amt
                brow["overdue"] += remaining_amt
                brow["overdue_count"] += 1
                overdue_count += 1
                overdue_days = (today - inv.due_date).days
                if overdue_days <= 30:
                    ageing[cur]["days_1_30"] += remaining_amt
                elif overdue_days <= 60:
                    ageing[cur]["days_31_60"] += remaining_amt
                elif overdue_days <= 90:
                    ageing[cur]["days_61_90"] += remaining_amt
                else:
                    ageing[cur]["days_90_plus"] += remaining_amt
            else:
                ageing[cur]["current"] += remaining_amt
        elif remaining_amt > 0 and inv.payment_status != "Rejected":
            ageing[cur]["current"] += remaining_amt

        elif inv.payment_status == "Rejected":
            row["rejected"] += net
            rejected_count += 1

    rows = sorted(
        groups.values(),
        key=lambda x: ((x["vendor"].name or "").lower(), x["currency"]),
    )
    currency_totals = _currency_totals(invoices)

    branch_currency_rows = []
    for b in branch_currency.values():
        b["vendor_count"] = len(b["vendor_ids"])
        del b["vendor_ids"]
        branch_currency_rows.append(b)
    branch_currency_rows.sort(key=lambda x: (x["branch"].lower(), x["currency"]))

    # Branch cards: each branch carries separate currency figures. Never sum unlike currencies.
    branch_cards_map = {}
    for b in branch_currency_rows:
        card = branch_cards_map.setdefault(b["branch"], {
            "branch": b["branch"],
            "invoice_count": 0,
            "vendor_count": set(),
            "currencies": [],
            "overdue_count": 0,
        })
        card["invoice_count"] += b["invoice_count"]
        card["overdue_count"] += b["overdue_count"]
        card["currencies"].append(b)
    for card in branch_cards_map.values():
        # Vendor counts are already de-duplicated within currency; calculate exact branch vendor count.
        card["vendor_count"] = len({
            inv.vendor_id for inv in invoices if branch_name(inv) == card["branch"]
        })
    branch_cards = sorted(branch_cards_map.values(), key=lambda x: x["branch"].lower())

    attention_invoices = sorted(
        [
            inv for inv in invoices
            if inv.payment_status in due_statuses and inv.due_date and inv.due_date < today
        ],
        key=lambda inv: (inv.due_date, -(float(inv.calculated_net_payable_amount or 0))),
    )[:8]

    summary_stats = {
        "total_invoices": len(invoices),
        "generated": generated_count,
        "paid": paid_count,
        "due": due_count,
        "overdue": overdue_count,
        "scheduled": scheduled_count,
        "on_hold": on_hold_count,
        "rejected": rejected_count,
        "upcoming_7": upcoming_7_count,
        "vendors": len(active_vendors),
        "branches": len(active_branches),
        "currencies": len(active_currencies),
    }

    filters = {
        "branch": selected_branch,
        "currency": selected_currency,
    }

    return render_template(
        "vendor_finance/summary.html",
        rows=rows,
        currency_totals=currency_totals,
        branch_currency_rows=branch_currency_rows,
        branch_cards=branch_cards,
        branch_options=branch_options,
        currency_options=currency_options,
        attention_invoices=attention_invoices,
        filters=filters,
        summary_stats=summary_stats,
        ageing=dict(sorted(ageing.items())),
        today=today,
    )


@vendor_finance_bp.route("/summary/generated")
@login_required
@require_perm("vendor_invoice.view")
def generated_invoices():
    invoices = (
        VendorInvoice.query
        .join(VendorMaster)
        .order_by(VendorInvoice.raised_at.desc(), VendorInvoice.id.desc())
        .all()
    )
    currency_totals = _currency_totals(invoices)
    generated_count = sum(1 for inv in invoices if inv.invoice_source == "GENERATED")
    uploaded_count = sum(1 for inv in invoices if inv.invoice_source != "GENERATED")
    return render_template(
        "vendor_finance/generated_invoices.html",
        invoices=invoices,
        currency_totals=currency_totals,
        generated_count=generated_count,
        uploaded_count=uploaded_count,
        today=date.today(),
    )


@vendor_finance_bp.route("/summary/paid")
@login_required
@require_perm("vendor_invoice.view")
def paid_invoices():
    invoices = (
        VendorInvoice.query
        .join(VendorMaster)
        .filter(VendorInvoice.payment_status == "Paid")
        .order_by(VendorInvoice.payment_date.desc(), VendorInvoice.id.desc())
        .all()
    )
    currency_totals = _currency_totals(invoices)
    return render_template(
        "vendor_finance/paid_invoices.html",
        invoices=invoices,
        currency_totals=currency_totals,
        today=date.today(),
    )


@vendor_finance_bp.route("/summary/due")
@login_required
@require_perm("vendor_invoice.view")
def due_invoices():
    today = date.today()
    due_statuses = ("Pending", "Scheduled", "Partially Paid", "On Hold")
    invoices = (
        VendorInvoice.query
        .join(VendorMaster)
        .filter(VendorInvoice.payment_status.in_(due_statuses))
        .order_by(VendorInvoice.due_date.asc(), VendorInvoice.id.desc())
        .all()
    )
    currency_totals = _currency_totals(invoices)

    ageing_rows = []
    for inv in invoices:
        overdue_days = 0
        ageing_label = "Current"
        if inv.due_date and inv.due_date < today:
            overdue_days = (today - inv.due_date).days
            if overdue_days <= 30:
                ageing_label = "1–30 days"
            elif overdue_days <= 60:
                ageing_label = "31–60 days"
            elif overdue_days <= 90:
                ageing_label = "61–90 days"
            else:
                ageing_label = "90+ days"
        ageing_rows.append((inv, overdue_days, ageing_label))

    return render_template(
        "vendor_finance/due_invoices.html",
        ageing_rows=ageing_rows,
        currency_totals=currency_totals,
        today=today,
        can_manage=current_user.has_perm("vendor_payment.manage"),
        payment_statuses=PAYMENT_STATUSES,
    )


@vendor_finance_bp.route("/tally-ledger-mapping", methods=["GET", "POST"])
@login_required
@require_perm("vendor_invoice.view")
def tally_ledger_mapping():
    """Manage the single Tally supplier ledger name stored against each vendor.

    This mapping is deliberately NOT branch-wise. The vendor ledger name is
    common across Tally companies; the target Tally company will later be
    resolved from the Vendor Invoice's bill-to branch.
    """
    if request.method == "POST":
        if not current_user.has_perm("vendor_payment.manage"):
            abort(403)

        vendor_id = request.form.get("vendor_id", type=int)
        tally_ledger_name = (request.form.get("tally_ledger_name") or "").strip()

        if not vendor_id:
            flash("Please select a valid vendor.", "danger")
            return redirect(url_for("vendor_finance.tally_ledger_mapping"))

        vendor = VendorMaster.query.get_or_404(vendor_id)
        old_ledger_name = vendor.tally_ledger_name
        vendor.tally_ledger_name = tally_ledger_name or None
        db.session.commit()

        log_audit(
            "VendorMaster",
            vendor.id,
            "UPDATE_TALLY_LEDGER",
            "tally_ledger_name",
            old_ledger_name,
            vendor.tally_ledger_name,
        )

        flash(
            "Tally ledger mapping updated for {} ({}).".format(
                vendor.name, vendor.external_translator_id
            ),
            "success",
        )
        return redirect(url_for(
            "vendor_finance.tally_ledger_mapping",
            q=(request.form.get("q") or "").strip(),
            currency=(request.form.get("currency") or "").strip(),
            mapping_status=(request.form.get("mapping_status") or "").strip(),
        ))

    q = (request.args.get("q") or "").strip()
    currency = (request.args.get("currency") or "").strip()
    mapping_status = (request.args.get("mapping_status") or "").strip().lower()

    query = VendorMaster.query

    if q:
        like = "%{}%".format(q)
        query = query.filter(or_(
            VendorMaster.external_translator_id.ilike(like),
            VendorMaster.name.ilike(like),
            VendorMaster.email.ilike(like),
            VendorMaster.tally_ledger_name.ilike(like),
        ))

    if currency:
        query = query.filter(func.upper(VendorMaster.currency) == currency.upper())

    if mapping_status == "mapped":
        query = query.filter(
            VendorMaster.tally_ledger_name.isnot(None),
            func.trim(VendorMaster.tally_ledger_name) != "",
        )
    elif mapping_status == "unmapped":
        query = query.filter(or_(
            VendorMaster.tally_ledger_name.is_(None),
            func.trim(VendorMaster.tally_ledger_name) == "",
        ))

    vendors = query.order_by(VendorMaster.name.asc()).all()

    all_vendor_rows = db.session.query(
        VendorMaster.tally_ledger_name, VendorMaster.currency
    ).all()
    total_count = len(all_vendor_rows)
    mapped_count = sum(
        1 for ledger_name, _ in all_vendor_rows if (ledger_name or "").strip()
    )
    unmapped_count = total_count - mapped_count
    currencies = sorted({
        (row[1] or "").strip().upper() for row in all_vendor_rows if (row[1] or "").strip()
    })

    return render_template(
        "vendor_finance/tally_ledger_mapping.html",
        vendors=vendors,
        q=q,
        selected_currency=currency,
        mapping_status=mapping_status,
        currencies=currencies,
        total_count=total_count,
        mapped_count=mapped_count,
        unmapped_count=unmapped_count,
        can_manage=current_user.has_perm("vendor_payment.manage"),
    )


@vendor_finance_bp.route("/jobcard-tracker")
@login_required
@require_perm("vendor_invoice.view")
def jobcard_tracker():
    """Finance view of the customer and vendor billing position for one jobcard."""
    q = (request.args.get("q") or "").strip()
    jobcard = None
    suggestions = []
    client_invoices = []
    vendor_rows = []
    client_summary = {
        "invoice_count": 0,
        "total": Decimal("0.00"),
        "collected": Decimal("0.00"),
        "outstanding": Decimal("0.00"),
    }

    if q:
        normalized = q.upper()
        jobcard = (
            OperationsJobcard.query
            .filter(func.upper(OperationsJobcard.jobcard_code) == normalized)
            .first()
        )
        if jobcard is None:
            suggestions = (
                OperationsJobcard.query
                .filter(OperationsJobcard.jobcard_code.ilike("%{}%".format(q)))
                .order_by(OperationsJobcard.id.desc())
                .limit(20)
                .all()
            )

    if jobcard is not None:
        # jobcard_id is the authoritative link. quote_id fallback keeps older
        # invoices visible if a historical row has not yet been backfilled.
        client_invoices = (
            Invoice.query
            .filter(
                or_(
                    Invoice.jobcard_id == jobcard.id,
                    and_(Invoice.jobcard_id.is_(None), Invoice.quote_id == jobcard.quote_id),
                )
            )
            .order_by(Invoice.invoice_date.desc(), Invoice.id.desc())
            .all()
        )

        for inv in client_invoices:
            gross = Decimal(str(inv.total_amount or 0)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            collected = Decimal(str(inv.collected_amount() or 0)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            remaining = max(Decimal("0.00"), gross - collected).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            inv.finance_collected = collected
            inv.finance_remaining = remaining
            inv.finance_payment_status = "Paid" if remaining <= Decimal("0.01") and gross > 0 else ("Partially Paid" if collected > 0 else (inv.status or "Unpaid"))
            client_summary["total"] += gross
            client_summary["collected"] += collected
            client_summary["outstanding"] += remaining
        client_summary["invoice_count"] = len(client_invoices)
        for key in ("total", "collected", "outstanding"):
            client_summary[key] = client_summary[key].quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

        assignments = (
            OperationsJobcardAssignment.query
            .join(OperationsJobcardService, OperationsJobcardService.id == OperationsJobcardAssignment.jobcard_service_id)
            .filter(
                OperationsJobcardService.jobcard_id == jobcard.id,
                OperationsJobcardAssignment.assigned_to_type == "VENDOR",
            )
            .order_by(OperationsJobcardAssignment.vendor_id.asc(), OperationsJobcardAssignment.id.asc())
            .all()
        )

        item_by_assignment = {}
        assignment_ids = [a.id for a in assignments]
        if assignment_ids:
            for item in VendorInvoiceItem.query.filter(VendorInvoiceItem.assignment_id.in_(assignment_ids)).all():
                item_by_assignment[item.assignment_id] = item

        grouped = {}
        for assignment in assignments:
            vendor = assignment.vendor
            vendor_key = assignment.vendor_id or "assignment-{}".format(assignment.id)
            row = grouped.setdefault(vendor_key, {
                "vendor": vendor,
                "assignments": [],
                "services": [],
                "assigned_amount": Decimal("0.00"),
                "vendor_invoices": {},
            })
            service = assignment.jobcard_service
            service_name = service.service_name if service else "—"
            if service_name and service_name not in row["services"]:
                row["services"].append(service_name)

            qty = Decimal(str(assignment.assigned_qty or 0))
            rate = Decimal(str(assignment.rate or 0))
            amount = rate if assignment.flat_rate else qty * rate
            amount = amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            row["assigned_amount"] += amount

            item = item_by_assignment.get(assignment.id)
            vendor_invoice = item.vendor_invoice if item else None
            row["assignments"].append({
                "assignment": assignment,
                "service_name": service_name,
                "amount": amount,
                "invoice_item": item,
                "vendor_invoice": vendor_invoice,
            })
            if vendor_invoice is not None:
                row["vendor_invoices"][vendor_invoice.id] = vendor_invoice

        for row in grouped.values():
            row["assigned_amount"] = row["assigned_amount"].quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            row["vendor_invoices"] = list(row["vendor_invoices"].values())
            row["invoice_count"] = len(row["vendor_invoices"])
            row["all_invoiced"] = bool(row["assignments"]) and all(x["vendor_invoice"] is not None for x in row["assignments"])
            row["any_invoiced"] = any(x["vendor_invoice"] is not None for x in row["assignments"])
            row["all_paid"] = bool(row["vendor_invoices"]) and all(inv.payment_status == "Paid" for inv in row["vendor_invoices"])
            row["vendor_invoices"].sort(key=lambda inv: (inv.invoice_date or date.min, inv.id or 0), reverse=True)
        vendor_rows = list(grouped.values())

    return render_template(
        "vendor_finance/jobcard_tracker.html",
        q=q,
        jobcard=jobcard,
        suggestions=suggestions,
        client_invoices=client_invoices,
        client_summary=client_summary,
        vendor_rows=vendor_rows,
        today=date.today(),
    )


@vendor_finance_bp.route("/")
@login_required
@require_perm("vendor_invoice.view")
def invoices():
    query, filters = _invoice_query()
    rows = query.order_by(VendorInvoice.raised_at.desc(), VendorInvoice.id.desc()).all()
    currencies = [r[0] for r in db.session.query(VendorInvoice.currency).distinct().order_by(VendorInvoice.currency).all() if r[0]]
    all_invoices = VendorInvoice.query.all()
    stats = {"total":len(all_invoices),"pending":sum(i.payment_status=="Pending" for i in all_invoices),"scheduled":sum(i.payment_status=="Scheduled" for i in all_invoices),"paid":sum(i.payment_status=="Paid" for i in all_invoices),"partial":sum(i.payment_status=="Partially Paid" for i in all_invoices),"on_hold":sum(i.payment_status=="On Hold" for i in all_invoices)}
    return render_template("vendor_finance/invoices.html", invoices=rows, filters=filters, currencies=currencies, stats=stats, payment_statuses=PAYMENT_STATUSES, can_manage=current_user.has_perm("vendor_payment.manage"), today=date.today())


@vendor_finance_bp.route("/<int:invoice_id>")
@login_required
@require_perm("vendor_invoice.view")
def invoice_detail(invoice_id):
    invoice = VendorInvoice.query.get_or_404(invoice_id)
    return render_template(
        "vendor_finance/invoice_detail.html",
        invoice=invoice, payment_statuses=PAYMENT_STATUSES,
        can_manage=current_user.has_perm("vendor_payment.manage"), today=date.today(),
        payment_progress=_invoice_progress(invoice),
        payment_jobcards=_jobcard_payment_rows(invoice),
        payment_transactions=list(invoice.payment_transactions or []),
    )


@vendor_finance_bp.route("/<int:invoice_id>/sync-tally", methods=["POST"])
@login_required
@require_perm("vendor_payment.manage")
def sync_vendor_invoice_to_tally(invoice_id):
    invoice = VendorInvoice.query.get_or_404(invoice_id)

    # When Tally sync is triggered from the register, return the user to the
    # same filtered list instead of forcing them into the invoice detail page.
    return_to = (request.form.get("return_to") or "").strip()
    if not (return_to.startswith("/") and not return_to.startswith("//")):
        return_to = url_for("vendor_finance.invoice_detail", invoice_id=invoice.id)

    if invoice.tally_sync_status == "Synced":
        flash("Vendor invoice is already synced to Tally.", "warning")
        return redirect(return_to)

    if invoice.payment_status == "Rejected" or invoice.status == "REJECTED":
        flash("Rejected vendor invoices cannot be synced to Tally.", "danger")
        return redirect(return_to)

    try:
        svc = TallyService()
        svc.push_vendor_invoice(invoice)
        log_audit(
            "VendorInvoice", invoice.id, "TALLY_SYNC",
            "tally_sync_status", None, "Synced"
        )
        flash("Vendor invoice synced to Tally successfully.", "success")
    except Exception as exc:
        # TallyService persists Failed + error itself. Keep this route focused on
        # user feedback and leave the current client invoice sync untouched.
        current_app.logger.exception(
            "Vendor invoice Tally sync failed invoice_id=%s", invoice.id
        )
        flash(f"Vendor Tally sync failed: {exc}", "danger")

    return redirect(return_to)


@vendor_finance_bp.route("/<int:invoice_id>/download")
@login_required
@require_perm("vendor_invoice.view")
def download(invoice_id):
    invoice = VendorInvoice.query.get_or_404(invoice_id)
    if invoice.invoice_source == "GENERATED":
        generate_system_vendor_invoice_pdf(invoice, None)
    full_path = _safe_static_file(invoice.invoice_file_path)
    if not full_path: abort(404)
    return send_file(full_path, as_attachment=True, download_name=invoice.invoice_file_name)


def _parse_payment_date(raw):
    if not raw: return None
    return datetime.strptime(raw, "%Y-%m-%d").date()


def _set_non_payment_status(invoice, status, remarks=None):
    old_status = invoice.payment_status
    if status == "Rejected" and _invoice_progress(invoice)["paid"] > 0:
        raise ValueError("A partially/fully paid invoice cannot be rejected. Reverse/correct the payment first.")
    invoice.payment_status = status
    invoice.finance_remarks = remarks
    invoice.payment_updated_at = datetime.utcnow()
    invoice.payment_updated_by_id = current_user.id
    invoice.status = "REJECTED" if status == "Rejected" else ("ON_HOLD" if status == "On Hold" else "RAISED")
    return old_status


@vendor_finance_bp.route("/<int:invoice_id>/payment", methods=["POST"])
@login_required
@require_perm("vendor_payment.manage")
def update_payment(invoice_id):
    invoice = VendorInvoice.query.get_or_404(invoice_id)
    action = (request.form.get("payment_action") or "TRANSACTION").strip().upper()

    if action == "STATUS":
        status = (request.form.get("invoice_status") or "").strip()
        if status not in ("Pending", "On Hold", "Rejected"):
            flash("Please select a valid invoice control status.", "danger")
            return redirect(url_for("vendor_finance.invoice_detail", invoice_id=invoice.id))
        try:
            old_status = _set_non_payment_status(invoice, status, (request.form.get("finance_remarks") or "").strip() or None)
            db.session.commit()
            log_audit("VendorInvoice", invoice.id, "PAYMENT_STATUS_CONTROL", "payment_status", old_status, status)
            flash(f"Invoice status updated to {status}.", "success")
        except ValueError as exc:
            db.session.rollback(); flash(str(exc), "danger")
        return redirect(url_for("vendor_finance.invoice_detail", invoice_id=invoice.id))

    tx_status = (request.form.get("transaction_status") or "").strip()
    if tx_status not in ("Paid", "Scheduled"):
        flash("Choose Paid or Scheduled for the payment transaction.", "danger")
        return redirect(url_for("vendor_finance.invoice_detail", invoice_id=invoice.id))
    try:
        payment_date = _parse_payment_date((request.form.get("payment_date") or "").strip())
    except ValueError:
        flash("Invalid payment/scheduled date.", "danger")
        return redirect(url_for("vendor_finance.invoice_detail", invoice_id=invoice.id))
    if not payment_date:
        flash("Payment/Scheduled date is required.", "danger")
        return redirect(url_for("vendor_finance.invoice_detail", invoice_id=invoice.id))

    selected_keys = set(request.form.getlist("jobcards"))
    payment_scope = (request.form.get("payment_scope") or "PARTIAL").strip().upper()
    if payment_scope == "FULL":
        selected_keys = {r["key"] for r in _jobcard_payment_rows(invoice) if r["remaining"] > 0}

    is_inr = (invoice.currency or "").strip().upper() == "INR"
    tds_confirmed = request.form.get("tds_confirmed") == "1"
    if tx_status == "Paid" and is_inr and not invoice.tds_confirmed and not tds_confirmed:
        flash("Please confirm the 10% TDS deduction before recording an INR payment.", "danger")
        return redirect(url_for("vendor_finance.invoice_detail", invoice_id=invoice.id))

    try:
        if tx_status == "Paid" and is_inr and (tds_confirmed or invoice.tds_confirmed):
            _sync_tds(invoice, confirmed=True)
        tx = _record_jobcard_payment(
            invoice, tx_status, payment_date, selected_keys,
            (request.form.get("payment_reference") or "").strip() or None,
            (request.form.get("finance_remarks") or "").strip() or None,
        )
        invoice.finance_remarks = tx.remarks or invoice.finance_remarks
        progress = _refresh_invoice_payment_status(invoice)
        db.session.commit()
        log_audit("VendorInvoice", invoice.id, "PAYMENT_TRANSACTION", "payment_status", None, invoice.payment_status)
        label = "payment" if tx_status == "Paid" else "schedule"
        flash(f"{label.title()} recorded: {invoice.currency} {tx.amount:.2f}. Remaining: {invoice.currency} {progress['remaining']:.2f}.", "success")
    except ValueError as exc:
        db.session.rollback(); flash(str(exc), "danger")
    return redirect(url_for("vendor_finance.invoice_detail", invoice_id=invoice.id))


@vendor_finance_bp.route("/payment/<int:payment_id>/mark-paid", methods=["POST"])
@login_required
@require_perm("vendor_payment.manage")
def mark_scheduled_payment_paid(payment_id):
    payment = VendorInvoicePayment.query.get_or_404(payment_id)
    invoice = payment.invoice
    if payment.status != "Scheduled":
        flash("Only scheduled transactions can be marked Paid.", "warning")
        return redirect(url_for("vendor_finance.invoice_detail", invoice_id=invoice.id))
    try:
        paid_date = _parse_payment_date((request.form.get("payment_date") or "").strip())
    except ValueError:
        paid_date = None
    if not paid_date:
        flash("Payment date is required.", "danger")
        return redirect(url_for("vendor_finance.invoice_detail", invoice_id=invoice.id))
    is_inr = (invoice.currency or "").strip().upper() == "INR"
    if is_inr and not invoice.tds_confirmed and request.form.get("tds_confirmed") != "1":
        flash("Please confirm TDS before marking this scheduled INR payment Paid.", "danger")
        return redirect(url_for("vendor_finance.invoice_detail", invoice_id=invoice.id))
    if is_inr:
        _sync_tds(invoice, confirmed=True)
    payment.status = "Paid"
    payment.payment_date = paid_date
    payment.reference = (request.form.get("payment_reference") or payment.reference or "").strip() or None
    payment.remarks = (request.form.get("remarks") or payment.remarks or "").strip() or None
    _refresh_invoice_payment_status(invoice)
    db.session.commit()
    log_audit("VendorInvoicePayment", payment.id, "SCHEDULE_MARKED_PAID", "status", "Scheduled", "Paid")
    flash("Scheduled payment marked Paid.", "success")
    return redirect(url_for("vendor_finance.invoice_detail", invoice_id=invoice.id))


@vendor_finance_bp.route("/bulk-payment", methods=["POST"])
@login_required
@require_perm("vendor_payment.manage")
def bulk_payment():
    ids = []
    for raw in request.form.getlist("invoice_ids"):
        try: ids.append(int(raw))
        except (TypeError, ValueError): pass
    if not ids:
        flash("Select at least one vendor invoice.", "warning")
        return redirect(request.referrer or url_for("vendor_finance.invoices"))
    invoices = VendorInvoice.query.filter(VendorInvoice.id.in_(ids)).order_by(VendorInvoice.due_date.asc(), VendorInvoice.id.asc()).all()
    workbench = []
    for invoice in invoices:
        progress = _invoice_progress(invoice)
        if progress["remaining"] <= 0 or invoice.payment_status == "Rejected":
            continue
        workbench.append({"invoice": invoice, "progress": progress, "jobcards": _jobcard_payment_rows(invoice)})
    if not workbench:
        flash("The selected invoices have no outstanding payable amount.", "warning")
        return redirect(request.referrer or url_for("vendor_finance.invoices"))
    return render_template("vendor_finance/bulk_payment.html", workbench=workbench, today=date.today())


@vendor_finance_bp.route("/bulk-payment/process", methods=["POST"])
@login_required
@require_perm("vendor_payment.manage")
def bulk_payment_process():
    ids = []
    for raw in request.form.getlist("invoice_ids"):
        try: ids.append(int(raw))
        except (TypeError, ValueError): pass
    tx_status = (request.form.get("transaction_status") or "").strip()
    if tx_status not in ("Paid", "Scheduled"):
        flash("Choose Paid or Scheduled.", "danger")
        return redirect(url_for("vendor_finance.invoices"))
    try:
        payment_date = _parse_payment_date((request.form.get("payment_date") or "").strip())
    except ValueError:
        payment_date = None
    if not payment_date:
        flash("Payment/Scheduled date is required.", "danger")
        return redirect(url_for("vendor_finance.invoices"))
    invoices = VendorInvoice.query.filter(VendorInvoice.id.in_(ids)).all()
    bulk_tds_confirmed = request.form.get("bulk_tds_confirmed") == "1"
    if tx_status == "Paid" and any((i.currency or "").strip().upper() == "INR" and not i.tds_confirmed for i in invoices) and not bulk_tds_confirmed:
        flash("Confirm 10% TDS for the selected INR invoices before recording payment.", "danger")
        return redirect(url_for("vendor_finance.invoices"))

    reference = (request.form.get("payment_reference") or "").strip() or None
    remarks = (request.form.get("finance_remarks") or "").strip() or None
    processed = 0
    skipped = []
    try:
        for invoice in invoices:
            selected = set(request.form.getlist(f"jobcards_{invoice.id}"))
            if not selected:
                skipped.append(invoice.vendor_invoice_no)
                continue
            if tx_status == "Paid" and (invoice.currency or "").strip().upper() == "INR":
                _sync_tds(invoice, confirmed=True)
            tx = _record_jobcard_payment(invoice, tx_status, payment_date, selected, reference, remarks)
            invoice.finance_remarks = remarks or invoice.finance_remarks
            _refresh_invoice_payment_status(invoice)
            processed += 1
            log_audit("VendorInvoice", invoice.id, "BULK_PAYMENT_TRANSACTION", "payment_status", None, invoice.payment_status)
        db.session.commit()
    except ValueError as exc:
        db.session.rollback(); flash(str(exc), "danger")
        return redirect(url_for("vendor_finance.invoices"))
    if processed:
        flash(f"Payment update recorded for {processed} invoice(s).", "success")
    if skipped:
        flash("Skipped invoices with no selected jobcards: " + ", ".join(skipped), "warning")
    return redirect(url_for("vendor_finance.invoices"))


@vendor_finance_bp.route("/export.xlsx")
@login_required
@require_perm("vendor_invoice.view")
def export_excel():
    """Export vendor invoices with user-selected columns in the requested order."""
    query, _ = _invoice_query()
    invoices = query.order_by(VendorInvoice.invoice_date.desc(), VendorInvoice.id.desc()).all()

    field_catalog = [
        ("vendor_invoice_no", "Vendor Invoice No"),
        ("bill_to_company", "Bill To Company"),
        ("invoice_branch", "Invoice Branch"),
        ("bill_to_address", "Bill To Address"),
        ("bill_to_gstin", "Bill To GSTIN"),
        ("invoice_date", "Invoice Date"),
        ("due_date", "Due Date"),
        ("invoice_source", "Invoice Source"),
        ("translator_id", "Translator ID"),
        ("translator_name", "Translator Name"),
        ("beneficiary_name", "Beneficiary Name"),
        ("vendor_billing_address", "Vendor Billing Address"),
        ("pan_number", "PAN Number"),
        ("gst_registered", "GST Registered"),
        ("vendor_gstin", "Vendor GSTIN"),
        ("bank_name", "Bank Name"),
        ("bank_address", "Bank Address"),
        ("bank_account_number", "Bank Account Number"),
        ("ifsc_code", "IFSC Code"),
        ("swift_bic", "SWIFT / BIC"),
        ("iban", "IBAN"),
        ("paypal_id", "PayPal ID"),
        ("currency", "Currency"),
        ("taxable_amount", "Taxable Amount"),
        ("gst_rate", "GST Rate %"),
        ("gst_amount", "GST Amount"),
        ("invoice_total", "Invoice Total"),
        ("tds_rate", "TDS Rate %"),
        ("tds_amount", "TDS Amount"),
        ("net_payable", "Net Payable"),
        ("paid_amount", "Paid Amount"),
        ("scheduled_amount", "Scheduled Amount"),
        ("remaining_amount", "Remaining Amount"),
        ("jobs", "Jobs"),
        ("jobcards", "Jobcards"),
        ("paid_jobcards", "Paid Jobcards"),
        ("scheduled_jobcards", "Scheduled Jobcards"),
        ("raised_at", "Raised At"),
        ("payment_status", "Payment Status"),
        ("payment_date", "Payment Date"),
        ("payment_reference", "Payment Reference"),
        ("finance_remarks", "Finance Remarks"),
    ]
    label_by_key = dict(field_catalog)

    # Repeated ?fields=... parameters preserve the exact order chosen in the UI.
    requested_fields = [f.strip() for f in request.args.getlist("fields") if f.strip()]
    selected_fields = []
    seen = set()
    for key in requested_fields:
        if key in label_by_key and key not in seen:
            selected_fields.append(key)
            seen.add(key)

    # Backward compatible: direct/old Export Excel links still export every field.
    if not selected_fields:
        selected_fields = [key for key, _ in field_catalog]

    wb = Workbook()
    ws = wb.active
    ws.title = "Vendor Invoices"
    headers = [label_by_key[key] for key in selected_fields]
    ws.append(headers)
    for c in ws[1]:
        c.font = Font(bold=True)
        c.alignment = Alignment(horizontal="center")

    for inv in invoices:
        jobcards = sorted({i.jobcard_code for i in inv.items if i.jobcard_code})
        _, rate, tds, net = _tds_values(inv)
        profile = inv.vendor.billing_profile if inv.vendor else None
        legacy_branch = None
        if not inv.bill_to_address:
            for item in inv.items:
                if item.customer_invoice and item.customer_invoice.company_branch:
                    legacy_branch = item.customer_invoice.company_branch
                    break

        bill_to_company = inv.bill_to_company_name or (legacy_branch.company.name if legacy_branch and legacy_branch.company else "")
        bill_to_address = inv.bill_to_address or (legacy_branch.branch_address if legacy_branch else "")
        bill_to_gst = inv.bill_to_gst_no or (legacy_branch.gst_no if legacy_branch else "")
        progress = _invoice_progress(inv)
        payment_rows = _jobcard_payment_rows(inv)

        values = {
            "vendor_invoice_no": inv.vendor_invoice_no,
            "bill_to_company": bill_to_company,
            "invoice_branch": inv.invoice_branch_display,
            "bill_to_address": bill_to_address,
            "bill_to_gstin": bill_to_gst,
            "invoice_date": inv.invoice_date,
            "due_date": inv.due_date,
            "invoice_source": inv.invoice_source,
            "translator_id": inv.vendor.external_translator_id if inv.vendor else "",
            "translator_name": inv.vendor.name if inv.vendor else "",
            "beneficiary_name": inv.vendor_beneficiary_name or (profile.beneficiary_name if profile else ""),
            "vendor_billing_address": inv.vendor_billing_address or (profile.billing_address if profile else ""),
            "pan_number": inv.vendor_pan_number or (profile.pan_number if profile else ""),
            "gst_registered": "Yes" if (inv.vendor_gst_registered if inv.vendor_gst_registered is not None else (profile.gst_registered if profile else False)) else "No",
            "vendor_gstin": inv.vendor_gstin or (profile.gstin if profile else ""),
            "bank_name": inv.vendor_bank_name or (profile.bank_name if profile else ""),
            "bank_address": inv.vendor_bank_address or (profile.bank_address if profile else ""),
            "bank_account_number": inv.vendor_bank_account_number or (profile.bank_account_number if profile else ""),
            "ifsc_code": inv.vendor_ifsc_code or (profile.ifsc_code if profile else ""),
            "swift_bic": inv.vendor_swift_code or (profile.swift_code if profile else ""),
            "iban": inv.vendor_iban or (profile.iban if profile else ""),
            "paypal_id": inv.vendor_paypal_id or (profile.paypal_id if profile else ""),
            "currency": inv.currency,
            "taxable_amount": float(inv.calculated_taxable_amount),
            "gst_rate": float(inv.gst_rate or 0),
            "gst_amount": float(inv.calculated_gst_amount),
            "invoice_total": float(inv.total_amount or 0),
            "tds_rate": float(rate),
            "tds_amount": float(tds),
            "net_payable": float(net),
            "paid_amount": float(progress["paid"]),
            "scheduled_amount": float(progress["scheduled"]),
            "remaining_amount": float(progress["remaining"]),
            "jobs": len(inv.items),
            "jobcards": ", ".join(jobcards),
            "paid_jobcards": ", ".join(sorted({r["jobcard_code"] for r in payment_rows if r["paid"] > 0})),
            "scheduled_jobcards": ", ".join(sorted({r["jobcard_code"] for r in payment_rows if r["scheduled"] > 0 and r["remaining"] > 0})),
            "raised_at": inv.raised_at,
            "payment_status": inv.payment_status,
            "payment_date": inv.payment_date,
            "payment_reference": inv.payment_reference or "",
            "finance_remarks": inv.finance_remarks or "",
        }
        ws.append([values.get(key, "") for key in selected_fields])

    for col in range(1, len(headers) + 1):
        max_len = len(headers[col - 1])
        for row in range(2, ws.max_row + 1):
            value = ws.cell(row=row, column=col).value
            if value is not None:
                max_len = max(max_len, len(str(value)))
        ws.column_dimensions[get_column_letter(col)].width = min(max_len + 2, 40)

    stream = BytesIO()
    wb.save(stream)
    stream.seek(0)
    return send_file(
        stream,
        as_attachment=True,
        download_name=f"vendor_invoices_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx",
        mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    )
