from collections import defaultdict
from datetime import date

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

from .. import check_branch, context_branch_ids, login_required, module_required, write_required
from ..db import commit, get_db, placeholders, q, x
from ..i18n import t
from ..ledger import AccountingError, audit, now
from ..money import to_int
from ..schedules import confirm_asset, depreciation_schedule, dispose_asset, post_depreciation
from ..attachments import remove_all as remove_attachments
from ..costcentres import options as cost_centre_options, parse as parse_cost_centre
from .common import accounts_list, branch_map, default_branch, partners_list, user_id

bp = Blueprint("assets", __name__, url_prefix="/assets")
bp.before_request(module_required("assets"))


def get_asset(asset_id):
    a = q("SELECT a.*, c.name_en AS cname_en, c.name_ar AS cname_ar, p.name_en AS pname_en, p.name_ar AS pname_ar "
          "FROM assets a JOIN asset_categories c ON c.id = a.category_id LEFT JOIN partners p ON p.id = a.partner_id "
          "WHERE a.id = ?", (asset_id,), one=True)
    if not a:
        abort(404)
    check_branch(a["branch_id"])
    return a


@bp.route("/")
@login_required
def index():
    ids = context_branch_ids()
    state = request.args.get("state", "")
    cat = request.args.get("category_id", type=int)
    rows = []
    if ids:
        sql = (f"SELECT a.*, c.name_en AS cname_en, c.name_ar AS cname_ar, "
               f"COALESCE((SELECT SUM(amount) FROM asset_lines WHERE asset_id = a.id AND move_id IS NOT NULL), 0) AS accumulated "
               f"FROM assets a JOIN asset_categories c ON c.id = a.category_id WHERE a.branch_id IN ({placeholders(ids)})")
        args = list(ids)
        if state:
            sql += " AND a.state = ?"
            args.append(state)
        if cat:
            sql += " AND a.category_id = ?"
            args.append(cat)
        rows = [dict(r) for r in q(sql + " ORDER BY a.code", args)]
    totals = defaultdict(lambda: [0, 0, 0])
    bm = branch_map()
    for r in rows:
        r["nbv"] = 0 if r["state"] == "disposed" else r["cost"] - r["accumulated"]
        if r["state"] != "disposed":
            cur = bm[r["branch_id"]]["currency"]
            totals[cur][0] += r["cost"]
            totals[cur][1] += r["accumulated"]
            totals[cur][2] += r["nbv"]
    return render_template("assets/list.html", rows=rows, totals=dict(totals), branches=bm, state=state,
                           categories=q("SELECT * FROM asset_categories ORDER BY name_en"), cat=cat)


@bp.route("/new", methods=["GET", "POST"])
@bp.route("/<int:asset_id>/edit", methods=["GET", "POST"])
@write_required
def form(asset_id=None):
    a = get_asset(asset_id) if asset_id else None
    if a and a["state"] != "draft":
        flash(t("Only draft documents can be edited."), "error")
        return redirect(url_for("assets.view", asset_id=asset_id))
    cats = q("SELECT * FROM asset_categories WHERE active = 1 ORDER BY name_en")
    if request.method == "POST":
        f = request.form
        try:
            branch_id = check_branch(f["branch_id"])
            cat = q("SELECT * FROM asset_categories WHERE id = ?", (int(f["category_id"]),), one=True)
            vals = {
                "code": f.get("code") or None, "name_en": f["name_en"], "name_ar": f.get("name_ar"),
                "category_id": cat["id"], "branch_id": branch_id,
                "partner_id": int(f["partner_id"]) if f.get("partner_id") else None,
                "serial_no": f.get("serial_no"), "location": f.get("location"), "custodian": f.get("custodian"),
                "acquisition_date": f["acquisition_date"], "start_date": f.get("start_date") or f["acquisition_date"],
                "cost": to_int(f["cost"]), "salvage": to_int(f.get("salvage") or 0),
                "method": f.get("method") or cat["method"],
                "life_months": int(f.get("life_months") or cat["life_months"]),
                "rate": float(f.get("rate") or cat["rate"] or 0), "notes": f.get("notes"),
                "invoice_id": int(f["invoice_id"]) if f.get("invoice_id") else None,
                "cost_centre_id": parse_cost_centre(f.get("cost_centre_id")),
            }
            if vals["cost"] <= 0 or vals["life_months"] <= 0:
                raise AccountingError(t("The amount must be greater than zero."))
            if a:
                x(f"UPDATE assets SET {', '.join(k + ' = ?' for k in vals)} WHERE id = ?", list(vals.values()) + [asset_id])
            else:
                if not vals["code"]:
                    n = q("SELECT COUNT(*) FROM assets", one=True)[0] + 1
                    vals["code"] = f"AST-{n:05d}"
                vals.update(created_by=user_id(), created_at=now(), state="draft")
                asset_id = x(f"INSERT INTO assets ({', '.join(vals)}) VALUES ({', '.join('?' * len(vals))})",
                             list(vals.values()))
            audit(user_id(), "save", "asset", asset_id, vals["code"] or "")
            commit()
            flash(t("Saved."), "success")
            return redirect(url_for("assets.view", asset_id=asset_id))
        except (AccountingError, ValueError, KeyError, TypeError) as e:
            get_db().rollback()
            flash(str(e) or t("invalid number"), "error")
            a = dict(request.form.items())
            a["id"] = asset_id
    if not a and request.args.get("invoice_id"):
        inv = q("SELECT * FROM invoices WHERE id = ?", (request.args.get("invoice_id", type=int),), one=True)
        if inv:
            check_branch(inv["branch_id"])
            first = q("SELECT description FROM invoice_lines WHERE invoice_id = ? ORDER BY sequence LIMIT 1",
                      (inv["id"],), one=True)
            a = {"branch_id": inv["branch_id"], "partner_id": inv["partner_id"], "invoice_id": inv["id"],
                 "acquisition_date": inv["date"], "start_date": inv["date"], "cost": inv["amount_untaxed"],
                 "name_en": first["description"] if first else inv["number"]}
    return render_template("assets/form.html", a=a, categories=cats, branches=branch_map(),
                           vendors=partners_list("vendor"), default_branch=default_branch(),
                           cost_centres=cost_centre_options(dict(a).get("cost_centre_id") if a else None),
                           today=date.today().isoformat())


@bp.route("/<int:asset_id>")
@login_required
def view(asset_id):
    a = get_asset(asset_id)
    lines = q("SELECT * FROM asset_lines WHERE asset_id = ? ORDER BY date", (asset_id,))
    preview = []
    if a["state"] == "draft":
        from ..schedules import branch_decimals
        preview = depreciation_schedule(a["cost"], a["salvage"], a["start_date"], a["life_months"], a["method"],
                                        a["rate"], branch_decimals(a["branch_id"]))
    posted = sum(ln["amount"] for ln in lines if ln["move_id"])
    branch = q("SELECT * FROM branches WHERE id = ?", (a["branch_id"],), one=True)
    return render_template("assets/view.html", a=a, lines=lines, preview=preview, posted=posted, branch=branch,
                           accounts=accounts_list(), today=date.today().isoformat())


@bp.route("/<int:asset_id>/<action>", methods=["POST"])
@write_required
def action(asset_id, action):
    a = get_asset(asset_id)
    f = request.form
    try:
        if action == "confirm":
            confirm_asset(asset_id, user_id(), f.get("credit_account_id") if f.get("post_acquisition") else None)
        elif action == "depreciate":
            n = post_depreciation(f.get("date") or date.today().isoformat(), [a["branch_id"]], user_id(), asset_id)
            flash(f"{n} {t('depreciation entries posted.')}", "success")
        elif action == "dispose":
            dispose_asset(asset_id, f["date"], to_int(f.get("amount") or 0),
                          int(f["proceeds_account_id"]) if f.get("proceeds_account_id") else None, user_id())
        elif action == "draft" and a["state"] == "running":
            if q("SELECT 1 FROM asset_lines WHERE asset_id = ? AND move_id IS NOT NULL", (asset_id,)) or a["acquisition_move_id"]:
                raise AccountingError(t("Depreciation is already posted for this asset."))
            x("DELETE FROM asset_lines WHERE asset_id = ?", (asset_id,))
            x("UPDATE assets SET state = 'draft' WHERE id = ?", (asset_id,))
        elif action == "delete" and a["state"] == "draft":
            x("DELETE FROM assets WHERE id = ?", (asset_id,))
            remove_attachments("asset", asset_id)
            audit(user_id(), "delete", "asset", asset_id, a["code"])
            commit()
            return redirect(url_for("assets.index"))
        else:
            raise AccountingError(t("This action is not allowed in the current state."))
        commit()
        if action != "depreciate":
            flash(t("Done."), "success")
    except (AccountingError, ValueError, KeyError) as e:
        get_db().rollback()
        flash(str(e), "error")
    return redirect(url_for("assets.view", asset_id=asset_id))
