from itertools import zip_longest

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

from .. import check_branch, currency_decimals, login_required, write_required
from ..db import commit, placeholders, q, x
from ..i18n import nm, t
from ..ledger import AccountingError, audit, check_journal, create_move, move_lines, post_move, set_move_state, \
    write_lines
from ..money import to_int
from ..attachments import counts as attachment_counts, remove_all as remove_attachments
from ..costcentres import check_lines as check_cost_centres, options as cost_centre_options, \
    parse as parse_cost_centre
from .common import apply_search, partner_search, product_search, accounts_list, branch_map, default_branch, journals_for, list_filters, partners_list, user_id

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


def get_move(move_id):
    m = q("SELECT m.*, j.code AS jcode, j.name_en AS jname_en, j.name_ar AS jname_ar, "
          "p.name_en AS pname_en, p.name_ar AS pname_ar "
          "FROM moves m JOIN journals j ON j.id = m.journal_id LEFT JOIN partners p ON p.id = m.partner_id "
          "WHERE m.id = ?", (move_id,), one=True)
    if not m:
        abort(404)
    check_branch(m["branch_id"])
    return m


@bp.route("/")
@login_required
def index():
    f = list_filters()
    if not f["branch_ids"]:
        return render_template("entries/list.html", rows=[], f=f, branches={})
    sql = (f"SELECT m.*, j.code AS jcode, p.name_en AS pname_en, p.name_ar AS pname_ar, "
           f"(SELECT SUM(debit) FROM move_lines WHERE move_id = m.id) AS amount "
           f"FROM moves m JOIN journals j ON j.id = m.journal_id LEFT JOIN partners p ON p.id = m.partner_id "
           f"WHERE m.branch_id IN ({placeholders(f['branch_ids'])})")
    args = list(f["branch_ids"])
    if f["date_from"]:
        sql += " AND m.date >= ?"
        args.append(f["date_from"])
    if f["date_to"]:
        sql += " AND m.date <= ?"
        args.append(f["date_to"])
    if f["state"]:
        sql += " AND m.state = ?"
        args.append(f["state"])
    mt = request.args.get("type", "")
    if mt:
        sql += " AND m.move_type = ?"
        args.append(mt)
    sql, args = apply_search(f, sql, args, [
        ("number", "Number", "m.name LIKE ?", "text"),
        ("ref", "Reference", "m.ref LIKE ?", "text"),
        ("narration", "Narration", "m.narration LIKE ?", "text"),
        ("account", "Account", "EXISTS (SELECT 1 FROM move_lines sl JOIN accounts sa ON sa.id = sl.account_id "
                               "WHERE sl.move_id = m.id AND (sa.code LIKE ? OR sa.name_en LIKE ? OR sa.name_ar LIKE ?))", "text"),
        ("partner", "Partner", f"({partner_search('p')}) OR EXISTS (SELECT 1 FROM move_lines sl JOIN partners sp "
                               f"ON sp.id = sl.partner_id WHERE sl.move_id = m.id AND ({partner_search('sp')}))", "text"),
        ("label", "Line label", "EXISTS (SELECT 1 FROM move_lines sl WHERE sl.move_id = m.id AND sl.label LIKE ?)", "text"),
        ("amount", "Amount", "EXISTS (SELECT 1 FROM move_lines sl WHERE sl.move_id = m.id AND (sl.debit = ? OR sl.credit = ?))",
         "amount")])
    rows = q(sql + " ORDER BY m.date DESC, m.id DESC LIMIT 1000", args)
    return render_template("entries/list.html", rows=rows, f=f, branches=branch_map(), mt=mt,
                           files=attachment_counts("move", [r["id"] for r in rows]))


def parse_lines(form):
    lines = []
    for acc, partner, lbl, dr, cr, cc in zip_longest(form.getlist("account_id"), form.getlist("partner_id"),
                                                     form.getlist("label"), form.getlist("debit"),
                                                     form.getlist("credit"), form.getlist("cost_centre_id"),
                                                     fillvalue=""):
        if not acc and not dr and not cr:
            continue
        if not acc:
            raise AccountingError(t("Every line needs an account."))
        try:
            debit, credit = to_int(dr), to_int(cr)
        except ValueError as e:
            raise AccountingError(str(e))
        lines.append({"account_id": int(acc), "partner_id": int(partner) if partner else None,
                      "label": lbl, "debit": debit, "credit": credit, "cost_centre_id": parse_cost_centre(cc)})
    check_cost_centres(lines)
    return lines


@bp.route("/new", methods=["GET", "POST"])
@bp.route("/<int:move_id>/edit", methods=["GET", "POST"])
@write_required
def form(move_id=None):
    m = get_move(move_id) if move_id else None
    if m and m["state"] != "draft":
        flash(t("Only draft entries can be edited."), "error")
        return redirect(url_for("entries.view", move_id=move_id))
    if m and m["move_type"] != "entry":
        flash(t("This entry is generated from a document; edit the document instead."), "error")
        return redirect(url_for("entries.view", move_id=move_id))
    lines = move_lines(move_id) if m else []
    if request.method == "GET" and not move_id and request.args.get("copy", type=int):
        # Duplicate: a new draft with the same journal, narration and lines, dated today
        src = get_move(request.args.get("copy", type=int))
        if src["move_type"] != "entry":
            flash(t("This entry is generated from a document; duplicate the document instead."), "error")
            return redirect(url_for("entries.view", move_id=src["id"]))
        from datetime import date
        m = dict(src)
        m.update(id=None, name=None, state="draft", date=date.today().isoformat())
        lines = move_lines(src["id"])
        flash(t("Copy of") + f" {src['name'] or t('Draft')}. " + t("Check it and save."), "info")
    if request.method == "POST":
        fm = request.form
        try:
            branch_id = check_branch(fm["branch_id"])
            check_journal(branch_id, int(fm["journal_id"]))
            if m:
                from ..ledger import check_number_kept
                check_number_kept(m["name"], m["branch_id"], branch_id, m["journal_id"], int(fm["journal_id"]),
                                  m["date"], fm["date"])
            lines = parse_lines(fm)
            post = fm.get("action") == "post"
            if m:
                x("UPDATE moves SET branch_id=?, journal_id=?, date=?, ref=?, narration=? WHERE id=?",
                  (branch_id, int(fm["journal_id"]), fm["date"], fm.get("ref"), fm.get("narration"), move_id))
                write_lines(move_id, branch_id, lines)
                if post:
                    post_move(move_id, user_id())
            else:
                move_id = create_move(branch_id, int(fm["journal_id"]), fm["date"], lines, user_id(),
                                      ref=fm.get("ref"), narration=fm.get("narration"), post=post)
            audit(user_id(), "save", "move", move_id)
            commit()
            flash(t("Entry posted.") if post else t("Draft saved."), "success")
            return redirect(url_for("entries.view", move_id=move_id))
        except AccountingError as e:
            flash(str(e), "error")
            m = dict(fm.items())
            m["id"] = move_id
            lines = [{"account_id": int(a) if a else None, "partner_id": int(p) if p else None, "label": lb,
                      "debit": to_int(d or 0), "credit": to_int(c or 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="")]
    branches = branch_map()
    return render_template("entries/form.html", m=m, lines=lines, branches=branches,
                           journals=journals_for(list(branches)), accounts=accounts_list(),
                           partners=partners_list(), cost_centres=cost_centre_options(), default_branch=default_branch())


@bp.route("/<int:move_id>")
@login_required
def view(move_id):
    m = get_move(move_id)
    lines = q("SELECT ml.*, a.code, a.name_en, a.name_ar, p.name_en AS pname_en, p.name_ar AS pname_ar, "
              "cc.code AS cc_code FROM move_lines ml JOIN accounts a ON a.id = ml.account_id "
              "LEFT JOIN partners p ON p.id = ml.partner_id LEFT JOIN cost_centres cc ON cc.id = ml.cost_centre_id "
              "WHERE ml.move_id = ? ORDER BY ml.id", (move_id,))
    doc = q("SELECT id, 'invoice' AS kind FROM invoices WHERE move_id = ? UNION "
            "SELECT id, 'payment' FROM payments WHERE move_id = ?", (move_id, move_id), one=True)
    linked = []
    if m["transfer_ref"]:
        linked = q("SELECT id, name, branch_id FROM moves WHERE transfer_ref = ? AND id != ?",
                   (m["transfer_ref"], move_id))
    branch = branch_map().get(m["branch_id"])
    if request.args.get("export"):
        from ..exports import Report, respond
        rep = Report("Journal Voucher", decimals=currency_decimals(branch["currency"]), signatures=True)
        rep.details = [("Number", m["name"] or t("Draft")), ("Date", m["date"]), ("Branch", f"{branch['code']} — {nm(branch)}"),
                       ("Reference", m["ref"] or "—"), ("Status", t(m["state"].capitalize())),
                       ("Currency", branch["currency"])]
        rep.column(t("Account"), width=2.4).column(t("Partner"), width=1.5).column(t("Label"), width=2.2) \
            .column(t("Debit"), "num").column(t("Credit"), "num")
        for ln in lines:
            rep.row([f"{ln['code']}  {nm(ln)}", nm({"name_en": ln["pname_en"], "name_ar": ln["pname_ar"]}) if ln["pname_en"] else "",
                     (ln["label"] or "") + (f" · {ln['cc_code']}" if ln["cc_code"] else ""), ln["debit"] or None, ln["credit"] or None])
        rep.row(["", "", t("Total"), sum(ln["debit"] for ln in lines), sum(ln["credit"] for ln in lines)], "grand")
        if m["narration"]:
            rep.notes.append(m["narration"])
        out = respond(rep, (m["name"] or "Draft").replace("/", "-"))
        if out:
            return out
    return render_template("entries/view.html", m=m, lines=lines, branch=branch,
                           doc=doc, linked=linked, branches=branch_map())


@bp.route("/<int:move_id>/<action>", methods=["POST"])
@write_required
def action(move_id, action):
    m = get_move(move_id)
    try:
        if m["move_type"] not in ("entry", "transfer"):
            raise AccountingError(t("This entry is generated from a document; edit the document instead."))
        if action == "post":
            post_move(move_id, user_id())
        elif action == "draft" and m["move_type"] == "entry":
            set_move_state(move_id, "draft", user_id())
        elif action == "cancel":
            if m["transfer_ref"]:
                for other in q("SELECT id FROM moves WHERE transfer_ref = ?", (m["transfer_ref"],)):
                    set_move_state(other["id"], "cancelled", user_id())
            else:
                set_move_state(move_id, "cancelled", user_id())
        elif action == "delete" and m["state"] == "draft":
            x("DELETE FROM moves WHERE id = ?", (move_id,))
            remove_attachments("move", move_id)
            audit(user_id(), "delete", "move", move_id)
            commit()
            flash(t("Deleted."), "success")
            return redirect(url_for("entries.index"))
        else:
            abort(400)
        commit()
        flash(t("Done."), "success")
    except AccountingError as e:
        flash(str(e), "error")
    return redirect(url_for("entries.view", move_id=move_id))


@bp.route("/bulk", methods=["POST"])
@write_required
def bulk():
    """Post the ticked draft journal entries."""
    from ..db import get_db
    ids = [int(v) for v in request.form.getlist("ids") if v.isdigit()][:500]
    back = request.referrer if (request.referrer or "").startswith(request.host_url) else url_for("entries.index")
    if request.form.get("action") != "post":
        abort(400)
    done, problems, db = 0, [], get_db()
    for i in ids:
        m = get_move(i)
        if m["state"] != "draft":
            continue
        db.execute("SAVEPOINT bulk_one")
        try:
            post_move(i, user_id())
            db.execute("RELEASE bulk_one")
            done += 1
        except AccountingError as e:
            db.execute("ROLLBACK TO bulk_one")
            db.execute("RELEASE bulk_one")
            problems.append(f"#{i}: {e}")
    commit()
    if done:
        flash(f"{done} " + t("entries posted."), "success")
    for p_ in problems[:10]:
        flash(p_, "error")
    if not done and not problems:
        flash(t("Tick at least one draft entry."), "error")
    return redirect(back)
