from datetime import date
from itertools import zip_longest

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

from .. import check_branch, context_branch_ids, currency_decimals, login_required, write_required
from ..db import commit, get_db, placeholders, q, x
from ..i18n import t
from ..ledger import AccountingError, audit, check_journal, now
from ..money import to_int
from ..costcentres import options as cost_centre_options
from ..recurring import FREQUENCIES, KINDS, amount, due_count, refresh, run, upcoming
from .common import accounts_list, branch_map, default_branch, journals_for, partners_list, taxes_list, user_id

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


def get_rec(rid):
    rec = q("SELECT r.*, p.name_en AS pname_en, p.name_ar AS pname_ar, j.code AS jcode FROM recurring r "
            "LEFT JOIN partners p ON p.id = r.partner_id JOIN journals j ON j.id = r.journal_id WHERE r.id = ?",
            (rid,), one=True)
    if not rec:
        abort(404)
    check_branch(rec["branch_id"])
    return rec


@bp.route("/")
@login_required
def index():
    ids = context_branch_ids()
    kind = request.args.get("kind", "")
    rows = []
    if ids:
        sql = (f"SELECT r.*, p.name_en AS pname_en, p.name_ar AS pname_ar, b.currency FROM recurring r "
               f"LEFT JOIN partners p ON p.id = r.partner_id JOIN branches b ON b.id = r.branch_id "
               f"WHERE r.branch_id IN ({placeholders(ids)})")
        args = list(ids)
        if kind in KINDS:
            sql += " AND r.kind = ?"
            args.append(kind)
        rows = [dict(r, amount=amount(r)) for r in q(sql + " ORDER BY r.state = 'done', r.next_date IS NULL, "
                                                     "r.next_date, r.name", args)]
    today = date.today().isoformat()
    return render_template("recurring/list.html", rows=rows, kind=kind, kinds=KINDS, freqs=dict(FREQUENCIES),
                           today=today, due=due_count(today, ids), branches=branch_map())


def parse(fm, kind, branch_id):
    lines = []
    if kind == "entry":
        from .entries import parse_lines
        for i, ln in enumerate(parse_lines(fm)):
            lines.append({"sequence": i, "account_id": ln["account_id"], "partner_id": ln["partner_id"],
                          "description": ln["label"], "debit": ln["debit"], "credit": ln["credit"],
                          "cost_centre_id": ln["cost_centre_id"]})
        if sum(ln["debit"] for ln in lines) != sum(ln["credit"] for ln in lines):
            raise AccountingError(t("The entry is not balanced."))
        if not any(ln["debit"] for ln in lines):
            raise AccountingError(t("The amount must be greater than zero."))
    else:
        from .invoices import parse_lines
        branch = q("SELECT * FROM branches WHERE id = ?", (branch_id,), one=True)
        lines = parse_lines(fm, currency_decimals(branch["currency"]))
        if sum(ln["subtotal"] for ln in lines) <= 0:
            raise AccountingError(t("The document total must be greater than zero."))
    if not lines:
        raise AccountingError(t("Add at least one line."))
    return lines


def prefill():
    """A new template copied from an existing invoice or journal entry ("Make recurring")."""
    inv_id, move_id = request.args.get("from_invoice", type=int), request.args.get("from_move", type=int)
    if inv_id:
        inv = q("SELECT * FROM invoices WHERE id = ?", (inv_id,), one=True)
        if not inv or inv["kind"] not in ("out_invoice", "in_invoice"):
            abort(404)
        check_branch(inv["branch_id"])
        rec = {"kind": inv["kind"], "branch_id": inv["branch_id"], "journal_id": inv["journal_id"],
               "partner_id": inv["partner_id"], "ref": inv["ref"], "notes": inv["notes"], "name": inv["ref"] or "",
               "start_date": add_month(inv["date"])}
        if inv["due_date"]:
            rec["due_days"] = (date.fromisoformat(inv["due_date"]) - date.fromisoformat(inv["date"])).days
        lines = [dict(r) for r in q("SELECT * FROM invoice_lines WHERE invoice_id = ? ORDER BY sequence, id", (inv_id,))]
        return rec, lines
    if move_id:
        m = q("SELECT * FROM moves WHERE id = ?", (move_id,), one=True)
        if not m:
            abort(404)
        check_branch(m["branch_id"])
        rec = {"kind": "entry", "branch_id": m["branch_id"], "journal_id": m["journal_id"], "ref": m["ref"],
               "notes": m["narration"], "name": m["narration"] or m["ref"] or "", "start_date": add_month(m["date"])}
        lines = [dict(r) for r in q("SELECT * FROM move_lines WHERE move_id = ? ORDER BY id", (move_id,))]
        return rec, lines
    return None, []


def add_month(d):
    from ..recurring import add_months
    return add_months(date.fromisoformat(d), 1).isoformat()


@bp.route("/new", methods=["GET", "POST"])
@bp.route("/<int:rid>/edit", methods=["GET", "POST"])
@write_required
def form(rid=None):
    rec = dict(get_rec(rid)) if rid else None
    lines = [dict(r) for r in q("SELECT * FROM recurring_lines WHERE recurring_id = ? ORDER BY sequence, id",
                                (rid,))] if rid else []
    if not rec:
        rec, lines = prefill()
    kind = (rec or {}).get("kind") or request.values.get("kind", "out_invoice")
    if kind not in KINDS:
        abort(404)
    if kind == "entry":
        lines = [dict(ln, label=ln.get("label") or ln.get("description")) for ln in lines]
    if request.method == "POST":
        fm = request.form
        try:
            branch_id = check_branch(fm["branch_id"])
            journal = check_journal(branch_id, int(fm["journal_id"]))
            if kind != "entry" and not fm.get("partner_id"):
                raise AccountingError(t("Choose a partner."))
            if not fm.get("name", "").strip():
                raise AccountingError(f"{t('Name')}: {t('is required')}")
            if not fm.get("start_date"):
                raise AccountingError(f"{t('First date')}: {t('is required')}")
            if fm.get("end_date") and fm["end_date"] < fm["start_date"]:
                raise AccountingError(t("The end date is before the first date."))
            freq = fm.get("frequency") if fm.get("frequency") in dict(FREQUENCIES) else "monthly"
            lines = parse(fm, kind, branch_id)
            vals = (fm["name"].strip(), branch_id, journal["id"], int(fm["partner_id"]) if fm.get("partner_id") and
                    kind != "entry" else None, fm.get("ref"), fm.get("notes"), int(fm.get("due_days") or 0), freq,
                    max(int(fm.get("every") or 1), 1), fm["start_date"], fm.get("end_date") or None,
                    int(fm["max_count"]) if (fm.get("max_count") or "").isdigit() and int(fm["max_count"]) else None,
                    1 if fm.get("auto_post") else 0, 1 if fm.get("auto_email") and fm.get("auto_post") else 0)
            if rid:
                if fm["start_date"] != rec["start_date"] and rec["done_count"]:
                    raise AccountingError(t("The first date cannot change once documents have been created."))
                x("UPDATE recurring SET name=?, branch_id=?, journal_id=?, partner_id=?, ref=?, notes=?, due_days=?, "
                  "frequency=?, every=?, start_date=?, end_date=?, max_count=?, auto_post=?, auto_email=? WHERE id = ?",
                  vals + (rid,))
                x("DELETE FROM recurring_lines WHERE recurring_id = ?", (rid,))
            else:
                rid = x("INSERT INTO recurring (name, branch_id, journal_id, partner_id, ref, notes, due_days, frequency, "
                        "every, start_date, end_date, max_count, auto_post, auto_email, kind, created_by, created_at) "
                        "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", vals + (kind, user_id(), now()))
            for i, ln in enumerate(lines):
                x("INSERT INTO recurring_lines (recurring_id, sequence, product_id, description, account_id, partner_id, "
                  "quantity, price_unit, tax_id, debit, credit, cost_centre_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
                  (rid, i, ln.get("product_id"), ln.get("description"), ln["account_id"], ln.get("partner_id"),
                   ln.get("quantity", 1), ln.get("price_unit", 0), ln.get("tax_id"), ln.get("debit", 0),
                   ln.get("credit", 0), ln.get("cost_centre_id")))
            refresh(rid)
            audit(user_id(), "save", "recurring", rid, fm["name"])
            commit()
            flash(t("Saved."), "success")
            return redirect(url_for("recurring.view", rid=rid))
        except (AccountingError, ValueError) as e:
            get_db().rollback()
            flash(str(e), "error")
            rec = {**(rec or {}), **fm.to_dict(), "kind": kind, "id": rid}
            for k in ("branch_id", "journal_id", "partner_id"):
                rec[k] = int(rec[k]) if rec.get(k) else None
            rec["auto_post"], rec["auto_email"] = bool(fm.get("auto_post")), bool(fm.get("auto_email"))
            lines = form_lines(fm, kind)
    branches = branch_map()
    jtype = {"out_invoice": ["sale"], "in_invoice": ["purchase"], "entry": None}[kind]
    from ..ledger import company
    return render_template("recurring/form.html", rec=rec, lines=lines, kind=kind, kinds=KINDS, freqs=FREQUENCIES,
                           branches=branches, journals=journals_for(list(branches), jtype) if jtype else
                           journals_for(list(branches)), accounts=accounts_list(),
                           partners=partners_list("customer" if kind == "out_invoice" else "vendor" if kind == "in_invoice"
                                                  else None),
                           taxes=taxes_list("sale" if kind == "out_invoice" else "purchase"),
                           products=q("SELECT * FROM products WHERE active = 1 ORDER BY code, name_en"),
                           grni=company()["grni_account_id"], default_branch=default_branch(),
                           cost_centres=cost_centre_options(),
                           today=date.today().isoformat())


def form_lines(fm, kind):
    """Lines as typed, to show the form again after an error."""
    if kind == "entry":
        return [{"account_id": int(a) if a else None, "partner_id": int(p) if p else None, "label": lb,
                 "debit": to_int(d or 0) if d.replace(".", "", 1).isdigit() else 0,
                 "credit": to_int(c or 0) if c.replace(".", "", 1).isdigit() else 0, "cost_centre_id": int(cc) if cc else None}
                for a, p, lb, d, c, cc in zip_longest(fm.getlist("account_id"), fm.getlist("partner_id"),
                                                      fm.getlist("label"), fm.getlist("debit"), fm.getlist("credit"),
                                                      fm.getlist("cost_centre_id"), fillvalue="")]
    return [{"description": d, "account_id": int(a) if a else None, "quantity": qq,
             "price_unit": to_int(p) if p.replace(".", "", 1).isdigit() else 0, "tax_id": int(tx) if tx else None,
             "product_id": int(pr) if pr else None, "cost_centre_id": int(cc) if cc else None}
            for d, a, qq, p, tx, pr, cc in zip_longest(fm.getlist("description"), fm.getlist("account_id"),
                                                       fm.getlist("quantity"), fm.getlist("price_unit"),
                                                       fm.getlist("tax_id"), fm.getlist("product_id"),
                                                       fm.getlist("cost_centre_id"), fillvalue="")]


@bp.route("/<int:rid>")
@login_required
def view(rid):
    rec = get_rec(rid)
    lines = q("SELECT l.*, a.code, a.name_en AS aname_en, a.name_ar AS aname_ar, tx.name_en AS tname_en, "
              "tx.name_ar AS tname_ar, p.name_en AS pname_en, p.name_ar AS pname_ar, cc.code AS cc_code FROM recurring_lines l "
              "JOIN accounts a ON a.id = l.account_id LEFT JOIN taxes tx ON tx.id = l.tax_id "
              "LEFT JOIN cost_centres cc ON cc.id = l.cost_centre_id "
              "LEFT JOIN partners p ON p.id = l.partner_id WHERE l.recurring_id = ? ORDER BY l.sequence, l.id", (rid,))
    runs = q("SELECT r.*, i.number AS inv_number, i.state AS inv_state, i.amount_total, m.name AS move_name, "
             "m.state AS move_state FROM recurring_runs r LEFT JOIN invoices i ON r.model = 'invoice' AND i.id = r.record_id "
             "LEFT JOIN moves m ON r.model = 'move' AND m.id = r.record_id WHERE r.recurring_id = ? ORDER BY r.date DESC",
             (rid,))
    branch = q("SELECT * FROM branches WHERE id = ?", (rec["branch_id"],), one=True)
    return render_template("recurring/view.html", rec=rec, lines=lines, runs=runs, branch=branch, kinds=KINDS,
                           freqs=dict(FREQUENCIES), upcoming=upcoming(rec), amount=amount(rec),
                           today=date.today().isoformat())


@bp.route("/run", methods=["POST"])
@write_required
def run_due():
    up_to = request.form.get("date") or date.today().isoformat()
    rid = request.form.get("rid", type=int)
    if rid:
        get_rec(rid)
    results = run(up_to, context_branch_ids(), user_id(), [rid] if rid else None)
    commit()
    made = [r for r in results if not r["error"]]
    if made:
        flash(f"{len(made)} {t('documents created.') if len(made) != 1 else t('document created.')}", "success")
    for r in results:
        if r["error"]:
            flash(f"{r['rec']['name']} ({r['date']}): {r['error']}", "error")
        elif r.get("note"):
            flash(f"{r['rec']['name']}: {r['note']}", "error")
    if not results:
        flash(t("Nothing is due."), "success")
    return redirect(request.form.get("next") or url_for("recurring.index"))


@bp.route("/<int:rid>/<action>", methods=["POST"])
@write_required
def action(rid, action):
    rec = get_rec(rid)
    if action == "pause" and rec["state"] == "active":
        x("UPDATE recurring SET state = 'paused' WHERE id = ?", (rid,))
    elif action == "resume" and rec["state"] == "paused":
        x("UPDATE recurring SET state = 'active' WHERE id = ?", (rid,))
        refresh(rid)
    elif action == "delete":
        if rec["done_count"]:
            flash(t("Documents were created from this template; pause it or set an end date instead."), "error")
            return redirect(url_for("recurring.view", rid=rid))
        x("DELETE FROM recurring WHERE id = ?", (rid,))
        audit(user_id(), "delete", "recurring", rid, rec["name"])
        commit()
        flash(t("Deleted."), "success")
        return redirect(url_for("recurring.index"))
    else:
        abort(400)
    audit(user_id(), action, "recurring", rid, rec["name"])
    commit()
    flash(t("Done."), "success")
    return redirect(url_for("recurring.view", rid=rid))
