from re import sub
from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required
from models import db, Customer, Subscription, SubscriptionUserChange
from decorators import roles_required
from audit_utils import write_audit

import calendar
from datetime import datetime, date

customers_bp = Blueprint("customers", __name__, url_prefix="/customers")


# ---------- Calendar helpers (for 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


# ---------- Customer CRUD ----------

@customers_bp.route("/")
@login_required
@roles_required("Admin", "Sales", "Accounts")
def list_customers():
    q = (request.args.get("q") or "").strip()
    status = (request.args.get("status") or "").strip()

    query = Customer.query

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

    if status in ["Active", "In-Active", "Name Changed"]:
        query = query.filter(Customer.status == status)

    customers = query.order_by(Customer.company_name.asc()).all()
    return render_template("customers_list.html", customers=customers, q=q, status=status)


@customers_bp.route("/add", methods=["GET", "POST"])
@login_required
@roles_required("Admin", "Sales")
def add_customer():
    if request.method == "POST":
        company_name = (request.form.get("company_name") or "").strip()
        bde_name = (request.form.get("bde_name") or "").strip()
        status = request.form.get("status") or "Active"

        contact_person = (request.form.get("contact_person") or "").strip()
        contact_email = (request.form.get("contact_email") or "").strip().lower()
        contact_phone = (request.form.get("contact_phone") or "").strip()

        email_to = (request.form.get("email_to") or "").strip()
        email_cc = (request.form.get("email_cc") or "").strip()
        remarks = (request.form.get("remarks") or "").strip()

        if not company_name:
            flash("Company name is required.", "danger")
            return render_template("customer_form.html", mode="add", customer=None)

        exists = Customer.query.filter_by(company_name=company_name).first()
        if exists:
            flash("Company already exists.", "danger")
            return render_template("customer_form.html", mode="add", customer=None)

        c = Customer(
            company_name=company_name,
            bde_name=bde_name or None,
            status=status,
            contact_person=contact_person or None,
            contact_email=contact_email or None,
            contact_phone=contact_phone or None,
            email_to=email_to or None,
            email_cc=email_cc or None,
            remarks=remarks or None
        )
        db.session.add(c)
        db.session.flush()  # ensure c.id exists

        write_audit(
            "Customer",
            c.id,
            "CREATE",
            summary="Customer created",
            after={"company_name": c.company_name, "status": c.status}
        )

        db.session.commit()
        flash("Customer added successfully.", "success")
        return redirect(url_for("customers.list_customers"))

    return render_template("customer_form.html", mode="add", customer=None)


@customers_bp.route("/<int:customer_id>")
@login_required
@roles_required("Admin", "Sales", "Accounts")
def view_customer(customer_id):
    customer = Customer.query.get_or_404(customer_id)
    return render_template("customer_view.html", customer=customer)


@customers_bp.route("/<int:customer_id>/edit", methods=["GET", "POST"])
@login_required
@roles_required("Admin", "Sales")
def edit_customer(customer_id):
    customer = Customer.query.get_or_404(customer_id)

    if request.method == "POST":
        before = {
            "company_name": customer.company_name,
            "status": customer.status,
            "bde_name": customer.bde_name,
            "contact_person": customer.contact_person,
            "contact_email": customer.contact_email,
            "contact_phone": customer.contact_phone,
            "email_to": customer.email_to,
            "email_cc": customer.email_cc,
            "remarks": customer.remarks
        }

        customer.company_name = (request.form.get("company_name") or "").strip()
        customer.bde_name = (request.form.get("bde_name") or "").strip() or None
        customer.status = request.form.get("status") or "Active"

        customer.contact_person = (request.form.get("contact_person") or "").strip() or None
        customer.contact_email = (request.form.get("contact_email") or "").strip().lower() or None
        customer.contact_phone = (request.form.get("contact_phone") or "").strip() or None

        customer.email_to = (request.form.get("email_to") or "").strip() or None
        customer.email_cc = (request.form.get("email_cc") or "").strip() or None
        customer.remarks = (request.form.get("remarks") or "").strip() or None

        if not customer.company_name:
            flash("Company name is required.", "danger")
            return render_template("customer_form.html", mode="edit", customer=customer)

        duplicate = Customer.query.filter(
            Customer.company_name == customer.company_name,
            Customer.id != customer.id
        ).first()
        if duplicate:
            flash("Another customer already has this company name.", "danger")
            return render_template("customer_form.html", mode="edit", customer=customer)

        after = {
            "company_name": customer.company_name,
            "status": customer.status,
            "bde_name": customer.bde_name,
            "contact_person": customer.contact_person,
            "contact_email": customer.contact_email,
            "contact_phone": customer.contact_phone,
            "email_to": customer.email_to,
            "email_cc": customer.email_cc,
            "remarks": customer.remarks
        }

        write_audit(
            "Customer",
            customer.id,
            "UPDATE",
            summary="Customer updated",
            before=before,
            after=after
        )

        db.session.commit()
        flash("Customer updated successfully.", "success")
        return redirect(url_for("customers.view_customer", customer_id=customer.id))

    return render_template("customer_form.html", mode="edit", customer=customer)


# ---------- Subscription (single active per customer) ----------

@customers_bp.route("/<int:customer_id>/subscription", methods=["GET", "POST"])
@login_required
@roles_required("Admin", "Sales")
def manage_subscription(customer_id):
    customer = Customer.query.get_or_404(customer_id)
    sub = Subscription.query.filter_by(customer_id=customer.id).first()

    if request.method == "POST":
        before = None
        if sub and sub.id:
            before = {
                "plan": sub.plan,
                "billing_cycle": sub.billing_cycle,
                "user_count": sub.user_count,
                "cost_per_user": sub.cost_per_user,
                "vendor_cost_per_user": sub.vendor_cost_per_user,
                "total_vendor_cost": sub.total_vendor_cost,
                "start_date": sub.start_date,
                "next_renewal_date": sub.next_renewal_date,
                "confirmation_status": sub.confirmation_status,
                "status": sub.status,
                "inactive_date": sub.inactive_date,
                "prorata_enabled": sub.prorata_enabled,
                "prorata_consumed": sub.prorata_consumed,
                "desktime_account_name": sub.desktime_account_name
            }

        plan = (request.form.get("plan") or "").strip() or None
        billing_cycle = request.form.get("billing_cycle") or "Monthly"
        user_count = int(request.form.get("user_count") or 0)

        cost_per_user = float(request.form.get("cost_per_user") or 0)
        vendor_cost_per_user = float(request.form.get("vendor_cost_per_user") or 0)
        total_vendor_cost = round(user_count * vendor_cost_per_user, 2)

        start_date_raw = (request.form.get("start_date") or "").strip()
        start_date = datetime.strptime(start_date_raw, "%Y-%m-%d").date() if start_date_raw else None

        desktime_account_name = (request.form.get("desktime_account_name") or "").strip() or None

        status = request.form.get("status") or "Active"
        confirmation_status = request.form.get("confirmation_status") or "Pending"

        inactive_date_raw = (request.form.get("inactive_date") or "").strip()
        inactive_date = datetime.strptime(inactive_date_raw, "%Y-%m-%d").date() if inactive_date_raw else None

        prorata_enabled = True if request.form.get("prorata_enabled") == "1" else False

        is_new = False
        if not sub:
            sub = Subscription(customer_id=customer.id)
            db.session.add(sub)
            db.session.flush()  # ensure sub.id exists
            is_new = True

        start_changed = (sub.start_date != start_date)
        cycle_changed = (sub.billing_cycle != billing_cycle)

        sub.plan = plan
        sub.billing_cycle = billing_cycle
        sub.user_count = user_count
        sub.cost_per_user = cost_per_user

        sub.vendor_cost_per_user = vendor_cost_per_user
        sub.total_vendor_cost = total_vendor_cost

        sub.start_date = start_date
        sub.desktime_account_name = desktime_account_name

        sub.status = status
        sub.confirmation_status = confirmation_status
        sub.inactive_date = inactive_date
        sub.prorata_enabled = prorata_enabled
        # IMPORTANT: do NOT reset prorata_consumed here

        # Calendar-aligned next renewal: cycle end containing start date
        if start_date and (sub.next_renewal_date is None or start_changed or cycle_changed):
            _, cycle_end = cycle_bounds(start_date, billing_cycle)
            sub.next_renewal_date = cycle_end

        after = {
            "plan": sub.plan,
            "billing_cycle": sub.billing_cycle,
            "user_count": sub.user_count,
            "cost_per_user": sub.cost_per_user,
            "vendor_cost_per_user": sub.vendor_cost_per_user,
            "total_vendor_cost": sub.total_vendor_cost,
            "start_date": sub.start_date,
            "next_renewal_date": sub.next_renewal_date,
            "confirmation_status": sub.confirmation_status,
            "status": sub.status,
            "inactive_date": sub.inactive_date,
            "prorata_enabled": sub.prorata_enabled,
            "prorata_consumed": sub.prorata_consumed,
            "desktime_account_name": sub.desktime_account_name
        }

        write_audit(
            "Subscription",
            sub.id,
            "CREATE" if is_new else "UPDATE",
            summary="Subscription saved",
            before=before,
            after=after
        )

        db.session.commit()
        flash("Subscription updated successfully.", "success")
        return redirect(url_for("customers.view_customer", customer_id=customer.id))

    from models import SubscriptionUserChange

    return render_template("subscription_form.html",customer=customer,sub=sub,SubscriptionUserChange=SubscriptionUserChange)


@customers_bp.route("/<int:customer_id>/subscription/user-change", methods=["POST"])
@login_required
@roles_required("Admin", "Sales")
def add_user_change(customer_id):
    customer = Customer.query.get_or_404(customer_id)
    sub = Subscription.query.filter_by(customer_id=customer.id).first_or_404()

    eff_raw = (request.form.get("effective_date") or "").strip()
    new_count = int(request.form.get("new_user_count") or 0)
    note = (request.form.get("note") or "").strip() or None

    if not eff_raw:
        flash("Effective date is required.", "danger")
        return redirect(url_for("customers.manage_subscription", customer_id=customer.id))

    eff_date = datetime.strptime(eff_raw, "%Y-%m-%d").date()

    old_count = int(sub.user_count or 0)
    delta = new_count - old_count

    # ✅ Initialize base users once (only if never set)
    # This locks "users already paid for this cycle" for correct prorata add billing.
    if not sub.cycle_base_user_count:
        sub.cycle_base_user_count = old_count

    before = {
        "user_count": old_count,
        "cycle_base_user_count": int(sub.cycle_base_user_count or 0),
        "total_vendor_cost": float(sub.total_vendor_cost or 0),
    }

    ch = SubscriptionUserChange(
        subscription_id=sub.id,
        effective_date=eff_date,
        old_user_count=old_count,
        new_user_count=new_count,
        delta_users=delta,
        note=note
    )
    db.session.add(ch)

    # Update subscription current totals immediately (for visibility + next cycle)
    sub.user_count = new_count
    sub.total_vendor_cost = round(float(sub.vendor_cost_per_user or 0) * float(new_count), 2)

    db.session.flush()  # ✅ ensure ch.id exists

    after = {
        "user_count": new_count,
        "delta_users": delta,
        "effective_date": str(eff_date),
        "total_vendor_cost": float(sub.total_vendor_cost or 0),
        "change_id": ch.id
    }

    write_audit(
        "SubscriptionUserChange",
        ch.id,
        "CREATE",
        summary=f"User count changed ({customer.company_name})",
        before=before,
        after=after
    )

    db.session.commit()
    flash("User change saved. Additions will be prorated in next invoice; removals apply next cycle.", "success")
    return redirect(url_for("customers.manage_subscription", customer_id=customer.id))