"""Month-end closing: post due depreciation and prepaid/accrual recognition, review drafts, set the lock date."""
import calendar
from datetime import date

from flask import Blueprint, flash, redirect, render_template, request, url_for

from .. import admin_required, context_branch_ids, has, write_required
from ..db import commit, get_db, placeholders, q, x
from ..i18n import t
from ..ledger import AccountingError, audit, company
from ..schedules import due_depreciation, due_recognitions, post_depreciation, post_recognitions
from .common import branch_map, user_id

bp = Blueprint("closing", __name__, url_prefix="/closing")


def last_month_end():
    d = date.today().replace(day=1)
    m = d.month - 1 or 12
    y = d.year if d.month > 1 else d.year - 1
    return date(y, m, calendar.monthrange(y, m)[1]).isoformat()


@bp.route("/", methods=["GET", "POST"])
@write_required
def index():
    ids = context_branch_ids()
    up_to = request.values.get("date") or last_month_end()
    if request.method == "POST":
        try:
            done = []
            if has("assets") and request.form.get("assets"):
                done.append(f"{post_depreciation(up_to, ids, user_id())} {t('depreciation entries posted.')}")
            if has("prepaid") and request.form.get("prepaid"):
                n, r = post_recognitions(up_to, ids, user_id())
                done.append(f"{n} {t('entries posted')}, {r} {t('reversals')}")
            commit()
            flash(" · ".join(done) or t("Nothing to post."), "success")
        except AccountingError as e:
            get_db().rollback()
            flash(str(e), "error")
        return redirect(url_for("closing.index", date=up_to))
    dep = due_depreciation(up_to, ids) if has("assets") else []
    rec, rev = due_recognitions(up_to, ids) if has("prepaid") else ([], [])
    ph = placeholders(ids) if ids else "NULL"
    drafts = {
        "entries": q(f"SELECT COUNT(*) FROM moves WHERE state = 'draft' AND date <= ? AND branch_id IN ({ph})",
                     [up_to] + ids, one=True)[0] if ids else 0,
        "invoices": q(f"SELECT COUNT(*) FROM invoices WHERE state = 'draft' AND date <= ? AND branch_id IN ({ph})",
                      [up_to] + ids, one=True)[0] if ids else 0,
        "pickings": q(f"SELECT COUNT(*) FROM pickings WHERE state = 'ready' AND date <= ? AND branch_id IN ({ph})",
                      [up_to] + ids, one=True)[0] if ids and has("inventory") else 0,
    }
    if has("inventory"):
        from ..stock import stock_matching
        m = stock_matching(ids, up_to)
        drafts["unmatched"] = sum(len(m[k]) for k in ("inv_not_delivered", "delivered_not_inv", "credit_not_returned"))
    from ..recurring import due_count
    from ..yearend import fiscal_years, preview
    drafts["recurring"] = due_count(up_to, ids)
    years = fiscal_years()
    done_years = [y for y in years if y[1] < date.today().isoformat()]
    fy = request.args.get("fy") or (done_years[0][0] if done_years else None)
    year_end, ye_rows = preview(fy, ids) if fy and ids else (None, [])
    return render_template("closing.html", up_to=up_to, dep=dep, rec=rec, rev=rev, drafts=drafts,
                           years=done_years, fy=fy, year_end=year_end, ye_rows=ye_rows,
                           branches=branch_map(), lock_date=company()["lock_date"])


@bp.route("/year", methods=["POST"])
@admin_required
def year_end():
    from ..yearend import close_year, reopen_year
    fy = request.form["fy"]
    ids = context_branch_ids()
    try:
        if request.form.get("action") == "reopen":
            n = reopen_year(fy, ids, user_id())
            flash(f"{n} {t('closing entries deleted. The year is open again.')}", "success")
        else:
            done = close_year(fy, ids, user_id())
            if request.form.get("lock") and done:
                from ..yearend import year_end_for
                x("UPDATE company SET lock_date = ? WHERE id = 1 AND (lock_date IS NULL OR lock_date < ?)",
                  (year_end_for(fy), year_end_for(fy)))
                audit(user_id(), "lock", "company", 1, f"lock_date={year_end_for(fy)}")
            flash(f"{len(done)} {t('closing entries posted.')}" if done else t("Nothing left to close for this year."),
                  "success")
        commit()
    except AccountingError as e:
        get_db().rollback()
        flash(str(e), "error")
    return redirect(url_for("closing.index", fy=fy) + "#year-end")


@bp.route("/lock", methods=["POST"])
@admin_required
def lock():
    d = request.form.get("lock_date") or None
    x("UPDATE company SET lock_date = ? WHERE id = 1", (d,))
    audit(user_id(), "lock", "company", 1, f"lock_date={d}")
    commit()
    flash(t("Saved."), "success")
    return redirect(url_for("closing.index", date=request.form.get("date")))
