

from datetime import date
from decimal import Decimal
from io import BytesIO

from flask import Blueprint, make_response, render_template, request, flash, redirect, url_for, session
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from app.services.gst_service import GSTService, GSTSettlementService, money
from app.services.posting_engine import PostingEngine, PostingError

from app.extensions import db
from app.models.accounting import (
    PurchaseInvoice,
    PurchaseInvoiceItem,
    SalesInvoice,
    SalesInvoiceItem,
    AccountLedger,
    GSTSettlement,
    Voucher,
)
from app.utils.permissions import current_company_id, login_required, permission_required


gst_reports_bp = Blueprint("gst_reports", __name__, url_prefix="/gst")


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


def parse_date(value):
    if not value:
        return None
    return date.fromisoformat(value)

def get_bank_cash_ledgers(company_id):
    return (
        AccountLedger.query.filter(
            AccountLedger.company_id == company_id,
            AccountLedger.is_deleted.is_(False),
            AccountLedger.ledger_type.in_(["bank", "cash"]),
        )
        .order_by(AccountLedger.ledger_name)
        .all()
    )


def positive(value):
    value = money(value)
    return value if value > 0 else Decimal("0.00")

@gst_reports_bp.route("/summary")
@login_required
@permission_required("reports.view")
def gst_summary():
    company_id = current_company_id()
    from_date = parse_date(request.args.get("from_date"))
    to_date = parse_date(request.args.get("to_date"))

    sales_query = (
        db.session.query(
            SalesInvoiceItem.gst_rate,
            db.func.coalesce(db.func.sum(SalesInvoiceItem.taxable_amount), 0).label("taxable"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.cgst_amount), 0).label("cgst"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.sgst_amount), 0).label("sgst"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.igst_amount), 0).label("igst"),
        )
        .join(SalesInvoice, SalesInvoice.id == SalesInvoiceItem.sales_invoice_id)
        .filter(
            SalesInvoice.company_id == company_id,
            SalesInvoice.is_deleted.is_(False),
            SalesInvoice.status == "posted",
        )
    )

    purchase_query = (
        db.session.query(
            PurchaseInvoiceItem.gst_rate,
            db.func.coalesce(db.func.sum(PurchaseInvoiceItem.taxable_amount), 0).label("taxable"),
            db.func.coalesce(db.func.sum(PurchaseInvoiceItem.cgst_amount), 0).label("cgst"),
            db.func.coalesce(db.func.sum(PurchaseInvoiceItem.sgst_amount), 0).label("sgst"),
            db.func.coalesce(db.func.sum(PurchaseInvoiceItem.igst_amount), 0).label("igst"),
        )
        .join(PurchaseInvoice, PurchaseInvoice.id == PurchaseInvoiceItem.purchase_invoice_id)
        .filter(
            PurchaseInvoice.company_id == company_id,
            PurchaseInvoice.is_deleted.is_(False),
            PurchaseInvoice.status == "posted",
        )
    )

    if from_date:
        sales_query = sales_query.filter(SalesInvoice.invoice_date >= from_date)
        purchase_query = purchase_query.filter(PurchaseInvoice.bill_date >= from_date)

    if to_date:
        sales_query = sales_query.filter(SalesInvoice.invoice_date <= to_date)
        purchase_query = purchase_query.filter(PurchaseInvoice.bill_date <= to_date)

    sales_rows_raw = sales_query.group_by(SalesInvoiceItem.gst_rate).order_by(SalesInvoiceItem.gst_rate).all()
    purchase_rows_raw = purchase_query.group_by(PurchaseInvoiceItem.gst_rate).order_by(PurchaseInvoiceItem.gst_rate).all()

    sales_rows = []
    purchase_rows = []

    output_taxable = Decimal("0.00")
    output_cgst = Decimal("0.00")
    output_sgst = Decimal("0.00")
    output_igst = Decimal("0.00")

    input_taxable = Decimal("0.00")
    input_cgst = Decimal("0.00")
    input_sgst = Decimal("0.00")
    input_igst = Decimal("0.00")

    for row in sales_rows_raw:
        taxable = money(row.taxable)
        cgst = money(row.cgst)
        sgst = money(row.sgst)
        igst = money(row.igst)
        total_tax = cgst + sgst + igst

        sales_rows.append({
            "gst_rate": money(row.gst_rate),
            "taxable": taxable,
            "cgst": cgst,
            "sgst": sgst,
            "igst": igst,
            "total_tax": total_tax,
        })

        output_taxable += taxable
        output_cgst += cgst
        output_sgst += sgst
        output_igst += igst

    for row in purchase_rows_raw:
        taxable = money(row.taxable)
        cgst = money(row.cgst)
        sgst = money(row.sgst)
        igst = money(row.igst)
        total_tax = cgst + sgst + igst

        purchase_rows.append({
            "gst_rate": money(row.gst_rate),
            "taxable": taxable,
            "cgst": cgst,
            "sgst": sgst,
            "igst": igst,
            "total_tax": total_tax,
        })

        input_taxable += taxable
        input_cgst += cgst
        input_sgst += sgst
        input_igst += igst

    total_output_gst = output_cgst + output_sgst + output_igst
    total_input_gst = input_cgst + input_sgst + input_igst
    net_gst = total_output_gst - total_input_gst

    summary = {
        "output_taxable": output_taxable,
        "output_cgst": output_cgst,
        "output_sgst": output_sgst,
        "output_igst": output_igst,
        "total_output_gst": total_output_gst,
        "input_taxable": input_taxable,
        "input_cgst": input_cgst,
        "input_sgst": input_sgst,
        "input_igst": input_igst,
        "total_input_gst": total_input_gst,
        "net_gst": net_gst,
        "net_status": "Payable" if net_gst >= 0 else "Receivable",
    }

    return render_template(
        "gst/summary.html",
        sales_rows=sales_rows,
        purchase_rows=purchase_rows,
        summary=summary,
        from_date=request.args.get("from_date") or "",
        to_date=request.args.get("to_date") or "",
    )


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


def parse_date(value):
    if not value:
        return None
    return date.fromisoformat(value)


def get_date_filters():
    return parse_date(request.args.get("from_date")), parse_date(request.args.get("to_date"))


def classify_gst_party(gstin):
    return "B2B" if gstin else "B2C"


def apply_sales_date_filter(query, from_date, to_date):
    if from_date:
        query = query.filter(SalesInvoice.invoice_date >= from_date)
    if to_date:
        query = query.filter(SalesInvoice.invoice_date <= to_date)
    return query


def apply_purchase_date_filter(query, from_date, to_date):
    if from_date:
        query = query.filter(PurchaseInvoice.bill_date >= from_date)
    if to_date:
        query = query.filter(PurchaseInvoice.bill_date <= to_date)
    return query


def posted_sales_invoice_query(company_id):
    return SalesInvoice.query.filter(
        SalesInvoice.company_id == company_id,
        SalesInvoice.is_deleted.is_(False),
        SalesInvoice.status == "posted",
    )


def posted_sales_item_query(company_id):
    return (
        db.session.query(SalesInvoiceItem)
        .join(SalesInvoice, SalesInvoice.id == SalesInvoiceItem.sales_invoice_id)
        .filter(
            SalesInvoice.company_id == company_id,
            SalesInvoice.is_deleted.is_(False),
            SalesInvoice.status == "posted",
            SalesInvoiceItem.taxable_amount > 0,
        )
    )


def posted_purchase_item_query(company_id):
    return (
        db.session.query(PurchaseInvoiceItem)
        .join(PurchaseInvoice, PurchaseInvoice.id == PurchaseInvoiceItem.purchase_invoice_id)
        .filter(
            PurchaseInvoice.company_id == company_id,
            PurchaseInvoice.is_deleted.is_(False),
            PurchaseInvoice.status == "posted",
            PurchaseInvoiceItem.taxable_amount > 0,
        )
    )


# ============================================================
# GSTR-1 REPORT WITH B2B/B2C CLASSIFICATION
# ============================================================
@gst_reports_bp.route("/gstr1")
@login_required
@permission_required("reports.view")
def gstr1_report():
    company_id = current_company_id()
    from_date, to_date = get_date_filters()

    invoice_query = posted_sales_invoice_query(company_id).order_by(
        SalesInvoice.invoice_date,
        SalesInvoice.invoice_no,
    )
    invoice_query = apply_sales_date_filter(invoice_query, from_date, to_date)
    invoices = invoice_query.all()

    invoice_rows = []
    b2b_rows = []
    b2c_rows = []

    total_invoice_value = Decimal("0.00")
    total_taxable = Decimal("0.00")
    total_cgst = Decimal("0.00")
    total_sgst = Decimal("0.00")
    total_igst = Decimal("0.00")

    b2b_taxable = Decimal("0.00")
    b2b_tax = Decimal("0.00")
    b2c_taxable = Decimal("0.00")
    b2c_tax = Decimal("0.00")

    for invoice in invoices:
        taxable = Decimal("0.00")
        cgst = Decimal("0.00")
        sgst = Decimal("0.00")
        igst = Decimal("0.00")

        for item in invoice.items:
            taxable += money(item.taxable_amount)
            cgst += money(item.cgst_amount)
            sgst += money(item.sgst_amount)
            igst += money(item.igst_amount)

        tax = cgst + sgst + igst
        invoice_value = money(invoice.total_amount)
        party_type = classify_gst_party(invoice.customer.gstin)

        row = {
            "invoice": invoice,
            "customer": invoice.customer,
            "party_type": party_type,
            "invoice_value": invoice_value,
            "taxable": taxable,
            "cgst": cgst,
            "sgst": sgst,
            "igst": igst,
            "total_tax": tax,
        }

        invoice_rows.append(row)

        if party_type == "B2B":
            b2b_rows.append(row)
            b2b_taxable += taxable
            b2b_tax += tax
        else:
            b2c_rows.append(row)
            b2c_taxable += taxable
            b2c_tax += tax

        total_invoice_value += invoice_value
        total_taxable += taxable
        total_cgst += cgst
        total_sgst += sgst
        total_igst += igst

    hsn_rows_raw = (
        db.session.query(
            SalesInvoiceItem.hsn_sac,
            SalesInvoiceItem.gst_rate,
            db.func.coalesce(db.func.sum(SalesInvoiceItem.qty), 0).label("qty"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.taxable_amount), 0).label("taxable"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.cgst_amount), 0).label("cgst"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.sgst_amount), 0).label("sgst"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.igst_amount), 0).label("igst"),
        )
        .join(SalesInvoice, SalesInvoice.id == SalesInvoiceItem.sales_invoice_id)
        .filter(
            SalesInvoice.company_id == company_id,
            SalesInvoice.is_deleted.is_(False),
            SalesInvoice.status == "posted",
            SalesInvoiceItem.taxable_amount > 0,
        )
    )
    hsn_rows_raw = apply_sales_date_filter(hsn_rows_raw, from_date, to_date)
    hsn_rows_raw = hsn_rows_raw.group_by(
        SalesInvoiceItem.hsn_sac,
        SalesInvoiceItem.gst_rate,
    ).order_by(SalesInvoiceItem.hsn_sac, SalesInvoiceItem.gst_rate).all()

    rate_rows_raw = (
        db.session.query(
            SalesInvoiceItem.gst_rate,
            db.func.coalesce(db.func.sum(SalesInvoiceItem.taxable_amount), 0).label("taxable"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.cgst_amount), 0).label("cgst"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.sgst_amount), 0).label("sgst"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.igst_amount), 0).label("igst"),
        )
        .join(SalesInvoice, SalesInvoice.id == SalesInvoiceItem.sales_invoice_id)
        .filter(
            SalesInvoice.company_id == company_id,
            SalesInvoice.is_deleted.is_(False),
            SalesInvoice.status == "posted",
            SalesInvoiceItem.taxable_amount > 0,
        )
    )
    rate_rows_raw = apply_sales_date_filter(rate_rows_raw, from_date, to_date)
    rate_rows_raw = rate_rows_raw.group_by(SalesInvoiceItem.gst_rate).order_by(SalesInvoiceItem.gst_rate).all()

    hsn_rows = []
    for row in hsn_rows_raw:
        cgst = money(row.cgst)
        sgst = money(row.sgst)
        igst = money(row.igst)
        hsn_rows.append({
            "hsn_sac": row.hsn_sac or "-",
            "gst_rate": money(row.gst_rate),
            "qty": money(row.qty),
            "taxable": money(row.taxable),
            "cgst": cgst,
            "sgst": sgst,
            "igst": igst,
            "total_tax": cgst + sgst + igst,
        })

    rate_rows = []
    for row in rate_rows_raw:
        cgst = money(row.cgst)
        sgst = money(row.sgst)
        igst = money(row.igst)
        rate_rows.append({
            "gst_rate": money(row.gst_rate),
            "taxable": money(row.taxable),
            "cgst": cgst,
            "sgst": sgst,
            "igst": igst,
            "total_tax": cgst + sgst + igst,
        })

    totals = {
        "invoice_value": total_invoice_value,
        "taxable": total_taxable,
        "cgst": total_cgst,
        "sgst": total_sgst,
        "igst": total_igst,
        "total_tax": total_cgst + total_sgst + total_igst,
        "b2b_count": len(b2b_rows),
        "b2b_taxable": b2b_taxable,
        "b2b_tax": b2b_tax,
        "b2c_count": len(b2c_rows),
        "b2c_taxable": b2c_taxable,
        "b2c_tax": b2c_tax,
    }

    return render_template(
        "gst/gstr1.html",
        invoice_rows=invoice_rows,
        b2b_rows=b2b_rows,
        b2c_rows=b2c_rows,
        hsn_rows=hsn_rows,
        rate_rows=rate_rows,
        totals=totals,
        from_date=request.args.get("from_date") or "",
        to_date=request.args.get("to_date") or "",
    )


# ============================================================
# GSTR-1 EXCEL EXPORT
# ============================================================
def style_sheet(ws):
    header_fill = PatternFill("solid", fgColor="1F4E78")
    header_font = Font(color="FFFFFF", bold=True)
    thin = Side(style="thin", color="D9E2F3")
    border = Border(left=thin, right=thin, top=thin, bottom=thin)

    for row in ws.iter_rows():
        for cell in row:
            cell.border = border
            cell.alignment = Alignment(vertical="center")

    for cell in ws[1]:
        cell.fill = header_fill
        cell.font = header_font
        cell.alignment = Alignment(horizontal="center", vertical="center")

    for column_cells in ws.columns:
        max_length = 0
        column = column_cells[0].column_letter
        for cell in column_cells:
            max_length = max(max_length, len(str(cell.value or "")))
        ws.column_dimensions[column].width = min(max_length + 3, 40)


def append_rows(ws, headers, rows):
    ws.append(headers)
    for row in rows:
        ws.append(row)
    style_sheet(ws)


@gst_reports_bp.route("/gstr1/export")
@login_required
@permission_required("reports.view")
def export_gstr1_excel():
    company_id = current_company_id()
    from_date, to_date = get_date_filters()

    invoices_query = posted_sales_invoice_query(company_id).order_by(SalesInvoice.invoice_date, SalesInvoice.invoice_no)
    invoices_query = apply_sales_date_filter(invoices_query, from_date, to_date)
    invoices = invoices_query.all()

    wb = Workbook()
    ws_b2b = wb.active
    ws_b2b.title = "B2B"
    ws_b2c = wb.create_sheet("B2C")
    ws_hsn = wb.create_sheet("HSN Summary")
    ws_rate = wb.create_sheet("Rate Summary")

    b2b_rows = []
    b2c_rows = []

    for inv in invoices:
        taxable = sum((money(i.taxable_amount) for i in inv.items), Decimal("0.00"))
        cgst = sum((money(i.cgst_amount) for i in inv.items), Decimal("0.00"))
        sgst = sum((money(i.sgst_amount) for i in inv.items), Decimal("0.00"))
        igst = sum((money(i.igst_amount) for i in inv.items), Decimal("0.00"))
        tax = cgst + sgst + igst
        row = [
            inv.invoice_no,
            inv.invoice_date.strftime("%d-%m-%Y"),
            inv.customer.customer_name,
            inv.customer.gstin or "",
            inv.customer.state or "",
            float(money(inv.total_amount)),
            float(taxable),
            float(cgst),
            float(sgst),
            float(igst),
            float(tax),
        ]
        if inv.customer.gstin:
            b2b_rows.append(row)
        else:
            b2c_rows.append(row)

    headers = [
        "Invoice No", "Date", "Customer", "GSTIN", "State", "Invoice Value",
        "Taxable", "CGST", "SGST", "IGST", "Total GST"
    ]
    append_rows(ws_b2b, headers, b2b_rows)
    append_rows(ws_b2c, headers, b2c_rows)

    hsn_query = (
        db.session.query(
            SalesInvoiceItem.hsn_sac,
            SalesInvoiceItem.gst_rate,
            db.func.coalesce(db.func.sum(SalesInvoiceItem.qty), 0).label("qty"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.taxable_amount), 0).label("taxable"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.cgst_amount), 0).label("cgst"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.sgst_amount), 0).label("sgst"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.igst_amount), 0).label("igst"),
        )
        .join(SalesInvoice, SalesInvoice.id == SalesInvoiceItem.sales_invoice_id)
        .filter(
            SalesInvoice.company_id == company_id,
            SalesInvoice.is_deleted.is_(False),
            SalesInvoice.status == "posted",
            SalesInvoiceItem.taxable_amount > 0,
        )
    )
    hsn_query = apply_sales_date_filter(hsn_query, from_date, to_date)
    hsn_rows_raw = hsn_query.group_by(SalesInvoiceItem.hsn_sac, SalesInvoiceItem.gst_rate).all()

    hsn_rows = []
    for r in hsn_rows_raw:
        cgst = money(r.cgst)
        sgst = money(r.sgst)
        igst = money(r.igst)
        hsn_rows.append([
            r.hsn_sac or "-",
            float(money(r.gst_rate)),
            float(money(r.qty)),
            float(money(r.taxable)),
            float(cgst),
            float(sgst),
            float(igst),
            float(cgst + sgst + igst),
        ])

    append_rows(ws_hsn, ["HSN/SAC", "GST Rate", "Qty", "Taxable", "CGST", "SGST", "IGST", "Total GST"], hsn_rows)

    rate_query = (
        db.session.query(
            SalesInvoiceItem.gst_rate,
            db.func.coalesce(db.func.sum(SalesInvoiceItem.taxable_amount), 0).label("taxable"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.cgst_amount), 0).label("cgst"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.sgst_amount), 0).label("sgst"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.igst_amount), 0).label("igst"),
        )
        .join(SalesInvoice, SalesInvoice.id == SalesInvoiceItem.sales_invoice_id)
        .filter(
            SalesInvoice.company_id == company_id,
            SalesInvoice.is_deleted.is_(False),
            SalesInvoice.status == "posted",
            SalesInvoiceItem.taxable_amount > 0,
        )
    )
    rate_query = apply_sales_date_filter(rate_query, from_date, to_date)
    rate_rows_raw = rate_query.group_by(SalesInvoiceItem.gst_rate).all()

    rate_rows = []
    for r in rate_rows_raw:
        cgst = money(r.cgst)
        sgst = money(r.sgst)
        igst = money(r.igst)
        rate_rows.append([
            float(money(r.gst_rate)),
            float(money(r.taxable)),
            float(cgst),
            float(sgst),
            float(igst),
            float(cgst + sgst + igst),
        ])

    append_rows(ws_rate, ["GST Rate", "Taxable", "CGST", "SGST", "IGST", "Total GST"], rate_rows)

    output = BytesIO()
    wb.save(output)
    output.seek(0)

    filename = "gstr1_report.xlsx"
    response = make_response(output.getvalue())
    response.headers["Content-Disposition"] = f"attachment; filename={filename}"
    response.headers["Content-Type"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    return response


# ============================================================
# GSTR-3B SUMMARY
# ============================================================
@gst_reports_bp.route("/gstr3b")
@login_required
@permission_required("reports.view")
def gstr3b_report():
    company_id = current_company_id()
    from_date, to_date = get_date_filters()

    sales_query = (
        db.session.query(
            db.func.coalesce(db.func.sum(SalesInvoiceItem.taxable_amount), 0).label("taxable"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.cgst_amount), 0).label("cgst"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.sgst_amount), 0).label("sgst"),
            db.func.coalesce(db.func.sum(SalesInvoiceItem.igst_amount), 0).label("igst"),
        )
        .join(SalesInvoice, SalesInvoice.id == SalesInvoiceItem.sales_invoice_id)
        .filter(
            SalesInvoice.company_id == company_id,
            SalesInvoice.is_deleted.is_(False),
            SalesInvoice.status == "posted",
            SalesInvoiceItem.taxable_amount > 0,
        )
    )
    sales_query = apply_sales_date_filter(sales_query, from_date, to_date)
    sales = sales_query.one()

    purchase_query = (
        db.session.query(
            db.func.coalesce(db.func.sum(PurchaseInvoiceItem.taxable_amount), 0).label("taxable"),
            db.func.coalesce(db.func.sum(PurchaseInvoiceItem.cgst_amount), 0).label("cgst"),
            db.func.coalesce(db.func.sum(PurchaseInvoiceItem.sgst_amount), 0).label("sgst"),
            db.func.coalesce(db.func.sum(PurchaseInvoiceItem.igst_amount), 0).label("igst"),
        )
        .join(PurchaseInvoice, PurchaseInvoice.id == PurchaseInvoiceItem.purchase_invoice_id)
        .filter(
            PurchaseInvoice.company_id == company_id,
            PurchaseInvoice.is_deleted.is_(False),
            PurchaseInvoice.status == "posted",
            PurchaseInvoiceItem.taxable_amount > 0,
        )
    )
    purchase_query = apply_purchase_date_filter(purchase_query, from_date, to_date)
    purchase = purchase_query.one()

    outward_taxable = money(sales.taxable)
    outward_igst = money(sales.igst)
    outward_cgst = money(sales.cgst)
    outward_sgst = money(sales.sgst)
    outward_total_tax = outward_igst + outward_cgst + outward_sgst

    itc_taxable = money(purchase.taxable)
    itc_igst = money(purchase.igst)
    itc_cgst = money(purchase.cgst)
    itc_sgst = money(purchase.sgst)
    itc_total = itc_igst + itc_cgst + itc_sgst

    net_igst = outward_igst - itc_igst
    net_cgst = outward_cgst - itc_cgst
    net_sgst = outward_sgst - itc_sgst
    net_total = outward_total_tax - itc_total

    summary = {
        "outward_taxable": outward_taxable,
        "outward_igst": outward_igst,
        "outward_cgst": outward_cgst,
        "outward_sgst": outward_sgst,
        "outward_total_tax": outward_total_tax,
        "itc_taxable": itc_taxable,
        "itc_igst": itc_igst,
        "itc_cgst": itc_cgst,
        "itc_sgst": itc_sgst,
        "itc_total": itc_total,
        "net_igst": net_igst,
        "net_cgst": net_cgst,
        "net_sgst": net_sgst,
        "net_total": net_total,
        "net_status": "Payable" if net_total >= 0 else "Receivable",
    }

    return render_template(
        "gst/gstr3b.html",
        summary=summary,
        from_date=request.args.get("from_date") or "",
        to_date=request.args.get("to_date") or "",
    )

@gst_reports_bp.route("/settlement", methods=["GET", "POST"])
@login_required
@permission_required("vouchers.create")
def gst_settlement_preview():
    company_id = current_company_id()
    from_date = parse_date(request.values.get("from_date"))
    to_date = parse_date(request.values.get("to_date"))

    settlement = None
    calc = None

    if from_date and to_date:
        settlement, calc, _ = GSTSettlementService(company_id).create_or_update_settlement(from_date, to_date)
        db.session.commit()

    bank_ledgers = get_bank_cash_ledgers(company_id)

    return render_template(
        "gst/settlement.html",
        from_date=request.values.get("from_date") or "",
        to_date=request.values.get("to_date") or "",
        settlement=settlement,
        calc=calc,
        bank_ledgers=bank_ledgers,
    )


@gst_reports_bp.route("/settlement/post-setoff", methods=["POST"])
@login_required
@permission_required("vouchers.create")
def post_gst_setoff():
    company_id = current_company_id()
    from_date = parse_date(request.form.get("from_date"))
    to_date = parse_date(request.form.get("to_date"))

    settlement, calc, can_update = GSTSettlementService(company_id).create_or_update_settlement(from_date, to_date)

    if settlement.status in ["setoff_posted", "paid"]:
        flash("GST set-off already posted for this period.", "warning")
        return redirect(url_for("gst_reports.gst_settlement_preview", from_date=from_date, to_date=to_date))

    gst = GSTService(company_id)
    entries = []

    # Debit output ledgers to reduce liability
    if calc["setoff_cgst"] > 0:
        entries.append({
            "ledger_id": gst.output_cgst_ledger().id,
            "debit_amount": calc["setoff_cgst"],
            "credit_amount": 0,
            "line_narration": "GST CGST set-off",
        })
    if calc["setoff_sgst"] > 0:
        entries.append({
            "ledger_id": gst.output_sgst_ledger().id,
            "debit_amount": calc["setoff_sgst"],
            "credit_amount": 0,
            "line_narration": "GST SGST set-off",
        })
    if calc["setoff_igst"] > 0:
        entries.append({
            "ledger_id": gst.output_igst_ledger().id,
            "debit_amount": calc["setoff_igst"],
            "credit_amount": 0,
            "line_narration": "GST IGST set-off",
        })

    # Credit input ledgers to reduce ITC asset
    if calc["setoff_cgst"] > 0:
        entries.append({
            "ledger_id": gst.input_cgst_ledger().id,
            "debit_amount": 0,
            "credit_amount": calc["setoff_cgst"],
            "line_narration": "GST CGST ITC utilised",
        })
    if calc["setoff_sgst"] > 0:
        entries.append({
            "ledger_id": gst.input_sgst_ledger().id,
            "debit_amount": 0,
            "credit_amount": calc["setoff_sgst"],
            "line_narration": "GST SGST ITC utilised",
        })
    if calc["setoff_igst"] > 0:
        entries.append({
            "ledger_id": gst.input_igst_ledger().id,
            "debit_amount": 0,
            "credit_amount": calc["setoff_igst"],
            "line_narration": "GST IGST ITC utilised",
        })

    if not entries:
        flash("No GST set-off available for this period.", "warning")
        return redirect(url_for("gst_reports.gst_settlement_preview", from_date=from_date, to_date=to_date))

    try:
        engine = PostingEngine(company_id=company_id, user_id=session.get("user_id"))
        voucher = engine.create_voucher(
            voucher_date=to_date,
            type_code="JV",
            reference_no=f"GST-SETOFF-{from_date}-{to_date}",
            narration=f"GST input-output set-off for {from_date} to {to_date}",
            entries=entries,
            source_module="gst",
            source_doc_type="gst_setoff",
            source_doc_id=settlement.id,
            auto_approve=True,
            auto_post=True,
        )

        settlement.setoff_voucher_id = voucher.id
        settlement.status = "setoff_posted"
        db.session.commit()
        flash(f"GST set-off voucher {voucher.voucher_no} posted successfully.", "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("gst_reports.gst_settlement_preview", from_date=from_date, to_date=to_date))

@gst_reports_bp.route("/settlement/pay", methods=["POST"])
@login_required
@permission_required("vouchers.create")
def pay_gst_liability():
    company_id = current_company_id()

    from_date = parse_date(request.form.get("from_date"))
    to_date = parse_date(request.form.get("to_date"))
    payment_date = parse_date(request.form.get("payment_date")) or to_date
    paid_from_ledger_id = request.form.get("paid_from_ledger_id", type=int)
    challan_no = request.form.get("challan_no")
    challan_date = parse_date(request.form.get("challan_date"))
    payment_reference_no = request.form.get("payment_reference_no")
    payment_remarks = request.form.get("payment_remarks")

    settlement = GSTSettlement.query.filter_by(
        company_id=company_id,
        from_date=from_date,
        to_date=to_date,
    ).first()

    if not settlement:
        flash("Please calculate GST settlement first.", "danger")
        return redirect(url_for("gst_reports.gst_settlement_preview"))

    if settlement.status == "paid":
        flash("GST payment already posted for this period.", "warning")
        return redirect(url_for("gst_reports.gst_settlement_preview", from_date=from_date, to_date=to_date))

    if settlement.status != "setoff_posted":
        flash("Please post GST set-off before making payment.", "warning")
        return redirect(url_for("gst_reports.gst_settlement_preview", from_date=from_date, to_date=to_date))

    if money(settlement.net_total) <= 0:
        flash("No GST payable for this period. Input credit will be carried forward.", "warning")
        return redirect(url_for("gst_reports.gst_settlement_preview", from_date=from_date, to_date=to_date))

    if not paid_from_ledger_id:
        flash("Please select bank/cash ledger for GST payment.", "danger")
        return redirect(url_for("gst_reports.gst_settlement_preview", from_date=from_date, to_date=to_date))

    paid_from_ledger = AccountLedger.query.filter_by(
        id=paid_from_ledger_id,
        company_id=company_id,
        is_deleted=False,
    ).first()

    if not paid_from_ledger:
        flash("Invalid bank/cash ledger selected.", "danger")
        return redirect(url_for("gst_reports.gst_settlement_preview", from_date=from_date, to_date=to_date))

    gst = GSTService(company_id)
    entries = []

    cgst_payable = positive(settlement.net_cgst)
    sgst_payable = positive(settlement.net_sgst)
    igst_payable = positive(settlement.net_igst)
    total_payable = cgst_payable + sgst_payable + igst_payable

    if total_payable <= 0:
        flash("No positive GST liability available for payment.", "warning")
        return redirect(url_for("gst_reports.gst_settlement_preview", from_date=from_date, to_date=to_date))

    if cgst_payable > 0:
        entries.append({
            "ledger_id": gst.output_cgst_ledger().id,
            "debit_amount": cgst_payable,
            "credit_amount": 0,
            "line_narration": f"CGST paid via challan {challan_no or '-'}",
        })

    if sgst_payable > 0:
        entries.append({
            "ledger_id": gst.output_sgst_ledger().id,
            "debit_amount": sgst_payable,
            "credit_amount": 0,
            "line_narration": f"SGST paid via challan {challan_no or '-'}",
        })

    if igst_payable > 0:
        entries.append({
            "ledger_id": gst.output_igst_ledger().id,
            "debit_amount": igst_payable,
            "credit_amount": 0,
            "line_narration": f"IGST paid via challan {challan_no or '-'}",
        })

    entries.append({
        "ledger_id": paid_from_ledger_id,
        "debit_amount": 0,
        "credit_amount": total_payable,
        "line_narration": f"GST payment for {from_date} to {to_date}",
    })

    try:
        engine = PostingEngine(company_id=company_id, user_id=session.get("user_id"))
        voucher = engine.create_voucher(
            voucher_date=payment_date,
            type_code="PV",
            reference_no=challan_no or f"GST-PAY-{from_date}-{to_date}",
            narration=payment_remarks or f"GST payment for {from_date} to {to_date}",
            entries=entries,
            source_module="gst",
            source_doc_type="gst_payment",
            source_doc_id=settlement.id,
            auto_approve=True,
            auto_post=True,
        )

        settlement.payment_voucher_id = voucher.id
        settlement.payment_date = payment_date
        settlement.paid_from_ledger_id = paid_from_ledger_id
        settlement.challan_no = challan_no
        settlement.challan_date = challan_date
        settlement.payment_reference_no = payment_reference_no
        settlement.payment_remarks = payment_remarks
        settlement.paid_amount = total_payable
        settlement.status = "paid"

        db.session.commit()
        flash(f"GST payment voucher {voucher.voucher_no} posted successfully.", "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("gst_reports.gst_settlement_preview", from_date=from_date, to_date=to_date))
    
@gst_reports_bp.route("/payments")
@login_required
@permission_required("reports.view")
def gst_payment_history():
    company_id = current_company_id()

    settlements = (
        GSTSettlement.query.filter(
            GSTSettlement.company_id == company_id,
            GSTSettlement.status.in_(["setoff_posted", "paid"]),
        )
        .order_by(GSTSettlement.to_date.desc())
        .all()
    )

    return render_template("gst/payment_history.html", settlements=settlements)