from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required
from models import db, Invoice, Customer, Subscription
from decorators import roles_required
from audit_utils import write_audit
from sqlalchemy import and_
from models import SubscriptionUserChange
import calendar
from datetime import date, datetime, timedelta

invoices_bp = Blueprint("invoices", __name__, url_prefix="/invoices")


# ---------- Calendar helpers (calendar-aligned billing) ----------

def end_of_month(d: date) -> date:
    return date(d.year, d.month, calendar.monthrange(d.year, d.month)[1])

def start_of_month(d: date) -> date:
    return date(d.year, d.month, 1)

def quarter_of_month(m: int) -> int:
    return (m - 1) // 3 + 1

def start_of_quarter(d: date) -> date:
    q = quarter_of_month(d.month)
    start_m = (q - 1) * 3 + 1
    return date(d.year, start_m, 1)

def end_of_quarter(d: date) -> date:
    q = quarter_of_month(d.month)
    end_m = q * 3
    return date(d.year, end_m, calendar.monthrange(d.year, end_m)[1])

def start_of_halfyear(d: date) -> date:
    return date(d.year, 1, 1) if d.month <= 6 else date(d.year, 7, 1)

def end_of_halfyear(d: date) -> date:
    return date(d.year, 6, 30) if d.month <= 6 else date(d.year, 12, 31)

def start_of_year(d: date) -> date:
    return date(d.year, 1, 1)

def end_of_year(d: date) -> date:
    return date(d.year, 12, 31)

def cycle_bounds(d: date, cycle: str):
    if cycle == "Monthly":
        return start_of_month(d), end_of_month(d)
    if cycle == "Quarterly":
        return start_of_quarter(d), end_of_quarter(d)
    if cycle == "Half Yearly":
        return start_of_halfyear(d), end_of_halfyear(d)
    if cycle == "Annually":
        return start_of_year(d), end_of_year(d)
    return start_of_month(d), end_of_month(d)

def next_cycle_end(after_date: date, cycle: str) -> date:
    _, e = cycle_bounds(after_date, cycle)
    return e

def inclusive_days(a: date, b: date) -> int:
    return (b - a).days + 1

def month_range(y: int, m: int):
    first = date(y, m, 1)
    last = date(y, m, calendar.monthrange(y, m)[1])
    return first, last

def months_in_cycle(cycle: str) -> int:
    return {"Monthly": 1, "Quarterly": 3, "Half Yearly": 6, "Annually": 12}.get(cycle, 1)


# ---------- Invoice screens ----------

@invoices_bp.route("/", methods=["GET"])
@login_required
@roles_required("Admin", "Sales", "Accounts")
def list_invoices():
    today = date.today()
    year = int(request.args.get("year") or today.year)
    month = int(request.args.get("month") or today.month)
    q = (request.args.get("q") or "").strip()

    query = Invoice.query.join(Customer)

    if q:
        like = f"%{q}%"
        query = query.filter(Customer.company_name.ilike(like))

    query = query.filter(Invoice.invoice_year == year, Invoice.invoice_month == month)

    invoices = query.order_by(Customer.company_name.asc()).all()
    customers = Customer.query.order_by(Customer.company_name.asc()).all()

    return render_template(
        "invoices_list.html",
        invoices=invoices,
        customers=customers,
        year=year,
        month=month,
        q=q
    )


@invoices_bp.route("/create", methods=["POST"])
@login_required
@roles_required("Admin", "Sales", "Accounts")
def create_invoice():
    customer_id = int(request.form.get("customer_id"))
    year = int(request.form.get("invoice_year"))
    month = int(request.form.get("invoice_month"))

    existing = Invoice.query.filter_by(customer_id=customer_id, invoice_year=year, invoice_month=month).first()
    if existing:
        flash("Invoice already exists for this customer and month.", "danger")
        return redirect(url_for("invoices.list_invoices", year=year, month=month))

    inv = Invoice(customer_id=customer_id, invoice_year=year, invoice_month=month)
    db.session.add(inv)
    db.session.commit()

    flash("Invoice created. Please edit details.", "success")
    return redirect(url_for("invoices.edit_invoice", invoice_id=inv.id))


@invoices_bp.route("/<int:invoice_id>/edit", methods=["GET", "POST"])
@login_required
@roles_required("Admin", "Sales", "Accounts")
def edit_invoice(invoice_id):
    inv = Invoice.query.get_or_404(invoice_id)

    if request.method == "POST":
        before = {
            "jobcard_no": inv.jobcard_no,
            "description": inv.description,
            "amount": inv.amount,
            "vendor_payment": inv.vendor_payment,
            "gst_applicable": inv.gst_applicable,
            "gst_rate": inv.gst_rate,
            "invoice_status": inv.invoice_status,
            "payment_status": inv.payment_status,
            "invoice_date": inv.invoice_date,
            "payment_received_date": inv.payment_received_date,
            "remarks": inv.remarks
        }

        inv.jobcard_no = (request.form.get("jobcard_no") or "").strip() or None
        inv.description = (request.form.get("description") or "").strip() or None

        inv.amount = float(request.form.get("amount") or 0)
        inv.vendor_payment = float(request.form.get("vendor_payment") or 0)

        inv.gst_applicable = True if request.form.get("gst_applicable") == "1" else False
        inv.gst_rate = float(request.form.get("gst_rate") or 18)

        inv.invoice_status = request.form.get("invoice_status") or "Pending"
        inv.payment_status = request.form.get("payment_status") or "Pending"

        invoice_date_raw = (request.form.get("invoice_date") or "").strip()
        payment_date_raw = (request.form.get("payment_received_date") or "").strip()

        inv.invoice_date = datetime.strptime(invoice_date_raw, "%Y-%m-%d").date() if invoice_date_raw else None
        inv.payment_received_date = datetime.strptime(payment_date_raw, "%Y-%m-%d").date() if payment_date_raw else None

        inv.remarks = (request.form.get("remarks") or "").strip() or None

        inv.recalc()

        after = {
            "jobcard_no": inv.jobcard_no,
            "description": inv.description,
            "amount": inv.amount,
            "vendor_payment": inv.vendor_payment,
            "gst_applicable": inv.gst_applicable,
            "gst_rate": inv.gst_rate,
            "invoice_status": inv.invoice_status,
            "payment_status": inv.payment_status,
            "invoice_date": inv.invoice_date,
            "payment_received_date": inv.payment_received_date,
            "remarks": inv.remarks
        }

        write_audit(
            "Invoice",
            inv.id,
            "UPDATE",
            summary="Invoice updated",
            before=before,
            after=after
        )

        db.session.commit()
        flash("Invoice updated.", "success")
        return redirect(url_for("invoices.list_invoices", year=inv.invoice_year, month=inv.invoice_month))

    return render_template("invoice_form.html", inv=inv)


# ---------- Generate Due Invoices (Mode A + calendar-based prorata) ----------

@invoices_bp.route("/generate-due", methods=["POST"])
@login_required
@roles_required("Admin", "Sales")
def generate_due_invoices():
    year = int(request.form.get("year"))
    month = int(request.form.get("month"))

    _, month_end = month_range(year, month)

    subs = Subscription.query.filter(
        Subscription.status == "Active",
        Subscription.next_renewal_date.isnot(None),
        Subscription.next_renewal_date <= month_end,
        Subscription.confirmation_status.in_(["Confirmed", "Not Required"])
    ).all()

    created = 0
    skipped_existing = 0

    for sub in subs:
        customer = sub.customer
        due_date = sub.next_renewal_date
        cycle = sub.billing_cycle

        cycle_start, cycle_end = cycle_bounds(due_date, cycle)

        inv_year = cycle_end.year
        inv_month = cycle_end.month

        existing = Invoice.query.filter_by(
            customer_id=customer.id,
            invoice_year=inv_year,
            invoice_month=inv_month
        ).first()
        if existing:
            skipped_existing += 1
            continue

        # ✅ Ensure base users are initialized (important for old subs)
        if not sub.cycle_base_user_count:
            sub.cycle_base_user_count = int(sub.user_count or 0)

        # --- Base (locked) users for current cycle ---
        base_users = int(sub.cycle_base_user_count or 0)

        monthly_customer_base = base_users * float(sub.cost_per_user)
        monthly_vendor_base = base_users * float(sub.vendor_cost_per_user)

        full_amount = round(monthly_customer_base * months_in_cycle(cycle), 2)
        full_vendor = round(monthly_vendor_base * months_in_cycle(cycle), 2)

        period_start = cycle_start
        period_end = cycle_end
        amt = full_amount
        vendor = full_vendor
        is_prorata = False

        # ---- First invoice prorata (calendar-based) ----
        if sub.prorata_enabled and (not sub.prorata_consumed) and sub.start_date:
            if cycle_start <= sub.start_date <= cycle_end:
                total_days = inclusive_days(cycle_start, cycle_end)
                bill_days = inclusive_days(sub.start_date, cycle_end)
                factor = bill_days / max(total_days, 1)

                period_start = sub.start_date
                period_end = cycle_end
                amt = round(full_amount * factor, 2)
                vendor = round(full_vendor * factor, 2)
                is_prorata = True

                sub.prorata_consumed = True

        # ---- NEW: User additions prorata (Option 2) ----
        total_days_cycle = inclusive_days(cycle_start, cycle_end)

        additions = SubscriptionUserChange.query.filter(
            SubscriptionUserChange.subscription_id == sub.id,
            SubscriptionUserChange.delta_users > 0,
            SubscriptionUserChange.billed_invoice_id.is_(None),
            SubscriptionUserChange.effective_date >= cycle_start,
            SubscriptionUserChange.effective_date <= cycle_end
        ).order_by(SubscriptionUserChange.effective_date.asc()).all()

        extra_customer = 0.0
        extra_vendor = 0.0

        for ch in additions:
            add_users = int(ch.delta_users)

            bill_days = inclusive_days(ch.effective_date, period_end)
            factor = bill_days / max(total_days_cycle, 1)

            add_cycle_customer = (add_users * float(sub.cost_per_user)) * months_in_cycle(cycle)
            add_cycle_vendor = (add_users * float(sub.vendor_cost_per_user)) * months_in_cycle(cycle)

            extra_customer += round(add_cycle_customer * factor, 2)
            extra_vendor += round(add_cycle_vendor * factor, 2)

        # Apply additions on top of base
        if extra_customer > 0 or extra_vendor > 0:
            amt = round(float(amt) + float(extra_customer), 2)
            vendor = round(float(vendor) + float(extra_vendor), 2)

        # ✅ ALWAYS create invoice (even if no additions)
        inv = Invoice(
            customer_id=customer.id,
            invoice_year=inv_year,
            invoice_month=inv_month,
            description=f"Auto-generated ({cycle})",
            amount=amt,
            vendor_payment=vendor,
            gst_applicable=False,
            gst_rate=18,
            invoice_status="Pending",
            payment_status="Pending",
            period_start=period_start,
            period_end=period_end,
            is_prorata=is_prorata
        )
        inv.recalc()
        db.session.add(inv)
        db.session.flush()  # ensure inv.id exists

        # Mark additions as billed
        for ch in additions:
            ch.billed_invoice_id = inv.id

        write_audit(
            "Invoice",
            inv.id,
            "GENERATE",
            summary=f"Invoice generated for {customer.company_name} {inv.invoice_month}/{inv.invoice_year}",
            after={
                "amount": float(inv.amount or 0),
                "vendor_payment": float(inv.vendor_payment or 0),
                "is_prorata": inv.is_prorata,
                "extra_customer": round(extra_customer, 2),
                "extra_vendor": round(extra_vendor, 2)
            }
        )

        # Advance renewal date (Mode A) + reset confirmation
        sub.next_renewal_date = next_cycle_end(period_end + timedelta(days=1), cycle)
        sub.confirmation_status = "Pending"

        # Next cycle base users = latest user_count (so removals apply next cycle)
        sub.cycle_base_user_count = int(sub.user_count or 0)
        sub.last_billed_date = period_end

        created += 1

    db.session.commit()
    flash(f"Generated {created} invoice(s). Skipped existing: {skipped_existing}.", "success")
    return redirect(url_for("invoices.list_invoices", year=year, month=month))