# ============================================================
# File: app/routes/reports.py
# ============================================================
from datetime import date

from flask import Blueprint, render_template, request
from app.models.accounting import AccountLedger, VoucherType
from app.services.report_service import ReportService
from app.utils.permissions import current_company_id, login_required, permission_required

from decimal import Decimal
from sqlalchemy import func

from app.extensions import db
from app.models.accounting import Vendor, PurchaseInvoice, PurchasePaymentAllocation

reports_bp = Blueprint("reports", __name__, url_prefix="/reports")


@reports_bp.route("/trial-balance")
@login_required
@permission_required("reports.view")
def trial_balance():
    company_id = current_company_id()

    from_date = request.args.get("from_date")
    to_date = request.args.get("to_date")

    parsed_from_date = date.fromisoformat(from_date) if from_date else None
    parsed_to_date = date.fromisoformat(to_date) if to_date else None

    service = ReportService(company_id)
    report = service.trial_balance(parsed_from_date, parsed_to_date)

    return render_template(
        "reports/trial_balance.html",
        report=report,
        from_date=from_date,
        to_date=to_date,
    )

@reports_bp.route("/profit-and-loss")
@login_required
@permission_required("reports.view")
def profit_and_loss():
    company_id = current_company_id()

    from_date = request.args.get("from_date")
    to_date = request.args.get("to_date")

    parsed_from_date = date.fromisoformat(from_date) if from_date else None
    parsed_to_date = date.fromisoformat(to_date) if to_date else None

    service = ReportService(company_id)
    report = service.profit_and_loss(parsed_from_date, parsed_to_date)

    return render_template(
        "reports/profit_and_loss.html",
        report=report,
        from_date=from_date,
        to_date=to_date,
    )

@reports_bp.route("/balance-sheet")
@login_required
@permission_required("reports.view")
def balance_sheet():
    company_id = current_company_id()

    as_on_date = request.args.get("as_on_date")
    parsed_as_on_date = date.fromisoformat(as_on_date) if as_on_date else None

    service = ReportService(company_id)
    report = service.balance_sheet(parsed_as_on_date)

    return render_template(
        "reports/balance_sheet.html",
        report=report,
        as_on_date=as_on_date,
    )

@reports_bp.route("/general-ledger")
@login_required
@permission_required("reports.view")
def general_ledger():
    company_id = current_company_id()

    ledger_id = request.args.get("ledger_id", type=int)
    from_date = request.args.get("from_date")
    to_date = request.args.get("to_date")

    parsed_from_date = date.fromisoformat(from_date) if from_date else None
    parsed_to_date = date.fromisoformat(to_date) if to_date else None

    ledgers = (
        AccountLedger.query.filter_by(
            company_id=company_id,
            is_deleted=False,
            active=True,
        )
        .order_by(AccountLedger.ledger_name)
        .all()
    )

    report = None
    if ledger_id:
        service = ReportService(company_id)
        report = service.general_ledger(ledger_id, parsed_from_date, parsed_to_date)

    return render_template(
        "reports/general_ledger.html",
        ledgers=ledgers,
        report=report,
        ledger_id=ledger_id,
        from_date=from_date,
        to_date=to_date,
    )

@reports_bp.route("/day-book")
@login_required
@permission_required("reports.view")
def day_book():
    company_id = current_company_id()

    from_date = request.args.get("from_date")
    to_date = request.args.get("to_date")
    voucher_type_id = request.args.get("voucher_type_id", type=int)

    parsed_from_date = date.fromisoformat(from_date) if from_date else None
    parsed_to_date = date.fromisoformat(to_date) if to_date else None

    voucher_types = (
        VoucherType.query.filter_by(
            company_id=company_id,
            is_deleted=False,
            active=True,
        )
        .order_by(VoucherType.type_name)
        .all()
    )

    service = ReportService(company_id)
    report = service.day_book(parsed_from_date, parsed_to_date, voucher_type_id)

    return render_template(
        "reports/day_book.html",
        report=report,
        voucher_types=voucher_types,
        from_date=from_date,
        to_date=to_date,
        voucher_type_id=voucher_type_id,
    )

@reports_bp.route("/vendor-outstanding")
@login_required
@permission_required("reports.view")
def vendor_outstanding():
    company_id = current_company_id()

    vendor_id = request.args.get("vendor_id", type=int)
    as_on_date = request.args.get("as_on_date")
    parsed_as_on_date = date.fromisoformat(as_on_date) if as_on_date else date.today()

    vendors = (
        Vendor.query.filter_by(company_id=company_id, is_deleted=False, active=True)
        .order_by(Vendor.vendor_name)
        .all()
    )

    query = PurchaseInvoice.query.filter(
        PurchaseInvoice.company_id == company_id,
        PurchaseInvoice.is_deleted.is_(False),
        PurchaseInvoice.status == "posted",
        PurchaseInvoice.voucher_id.isnot(None),
        PurchaseInvoice.bill_date <= parsed_as_on_date,
    )

    if vendor_id:
        query = query.filter(PurchaseInvoice.vendor_id == vendor_id)

    invoices = query.order_by(PurchaseInvoice.bill_date, PurchaseInvoice.bill_no).all()

    rows = []
    total_gross = Decimal("0.00")
    total_tds = Decimal("0.00")
    total_net = Decimal("0.00")
    total_paid = Decimal("0.00")
    total_balance = Decimal("0.00")

    for invoice in invoices:
        paid = db.session.query(
            func.coalesce(func.sum(PurchasePaymentAllocation.allocated_amount), 0)
        ).filter(
            PurchasePaymentAllocation.company_id == company_id,
            PurchasePaymentAllocation.purchase_invoice_id == invoice.id,
        ).scalar() or Decimal("0.00")

        gross_amount = Decimal(str(invoice.total_amount or 0))
        tds_amount = Decimal(str(invoice.tds_amount or 0))
        net_payable = Decimal(str(invoice.net_payable_amount or invoice.total_amount or 0))
        paid_amount = Decimal(str(paid))
        balance = net_payable - paid_amount

        if balance <= 0:
            continue

        age_days = (parsed_as_on_date - invoice.bill_date).days

        rows.append({
            "invoice": invoice,
            "vendor": invoice.vendor,
            "gross_amount": gross_amount,
            "tds_amount": tds_amount,
            "net_payable": net_payable,
            "paid_amount": paid_amount,
            "balance": balance,
            "age_days": age_days,
        })

        total_gross += gross_amount
        total_tds += tds_amount
        total_net += net_payable
        total_paid += paid_amount
        total_balance += balance

    report = {
        "rows": rows,
        "total_gross": total_gross,
        "total_tds": total_tds,
        "total_net": total_net,
        "total_paid": total_paid,
        "total_balance": total_balance,
        "count": len(rows),
    }

    return render_template(
        "reports/vendor_outstanding.html",
        vendors=vendors,
        vendor_id=vendor_id,
        as_on_date=as_on_date or parsed_as_on_date.isoformat(),
        report=report,
    )