"""Projects: register, project form (team, budget, milestones), project dashboard with budget / committed / actual,
progress billing and retention release."""
from datetime import date

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

from .. import check_branch, context_branch_ids, currency_decimals, login_required, module_required, write_required
from ..db import commit, get_db, q, x
from ..exports import Report, respond
from ..i18n import nm, t
from ..ledger import ROOT, AccountingError, audit
from ..money import to_int
from .. import projects as pj
from .common import branch_map, default_branch, list_filters, partners_list, taxes_list, user_id

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

STATE_LABEL = {"draft": "Draft", "active": "Active", "on_hold": "On hold", "closed": "Closed"}
CONTROL_LABEL = {"none": "No control", "warn": "Warn when over budget", "block": "Block when over budget"}


def get_project(pid):
    p = q("SELECT p.*, b.code AS bcode, b.currency, c.name_en AS cust_en, c.name_ar AS cust_ar, u.full_name AS manager, "
          "u.username AS manager_user, cc.code AS cc_code FROM projects p JOIN branches b ON b.id = p.branch_id "
          "LEFT JOIN partners c ON c.id = p.partner_id LEFT JOIN users u ON u.id = p.manager_id "
          "LEFT JOIN cost_centres cc ON cc.id = p.cost_centre_id WHERE p.id = ?", (pid,), one=True)
    if not p:
        abort(404)
    check_branch(p["branch_id"])
    return p


def users_list():
    return q("SELECT id, username, full_name FROM users WHERE active = 1 ORDER BY full_name, username")


def expense_accounts():
    return [a for a in q("SELECT * FROM accounts WHERE active = 1 ORDER BY code") if ROOT[a["kind"]] == "expense"]


@bp.route("/")
@login_required
def index():
    f = list_filters()
    state = request.args.get("state", "")
    mine = request.args.get("mine") == "1"
    rows = pj.list_rows(context_branch_ids(), state or None, f["search"], user_id() if mine else None)
    if request.args.get("export"):
        rep = Report("Projects", [t(STATE_LABEL[state]) if state else t("All projects")], landscape=True)
        rep.column(t("Code"), width=0.8).column(t("Project"), width=2).column(t("Customer"), width=1.6) \
            .column(t("Manager"), width=1.1).column(t("Contract value"), "num").column(t("Budget"), "num") \
            .column(t("Committed"), "num").column(t("Actual cost"), "num").column(t("Invoiced"), "num") \
            .column(t("Status"), width=0.8)
        for r in rows:
            rep.row([r["code"], nm(r), nm({"name_en": r["cust_en"], "name_ar": r["cust_ar"]}) if r["cust_en"] else "",
                     r["manager"] or "", r["contract_value"], r["budget"], r["committed"], r["actual"], r["billed"],
                     t(STATE_LABEL[r["state"]])])
        out = respond(rep, "projects")
        if out:
            return out
    return render_template("projects/index.html", rows=rows, f=f, state=state, mine=mine, states=STATE_LABEL,
                           branches=branch_map())


@bp.route("/new", methods=["GET", "POST"])
@bp.route("/<int:pid>/edit", methods=["GET", "POST"])
@write_required
def form(pid=None):
    p = get_project(pid) if pid else None
    if request.method == "POST":
        fm = request.form
        try:
            branch_id = check_branch(fm["branch_id"])
            vals = {"code": (fm.get("code") or "").strip().upper(), "name_en": (fm.get("name_en") or "").strip(),
                    "name_ar": (fm.get("name_ar") or "").strip() or None, "branch_id": branch_id,
                    "partner_id": int(fm["partner_id"]) if fm.get("partner_id") else None,
                    "manager_id": int(fm["manager_id"]) if fm.get("manager_id") else None,
                    "start_date": fm.get("start_date") or None, "end_date": fm.get("end_date") or None,
                    "site_address": fm.get("site_address") or None, "contract_value": to_int(fm.get("contract_value") or 0),
                    "retention_pct": float(fm.get("retention_pct") or 0), "budget_control": fm.get("budget_control"),
                    "revenue_account_id": int(fm["revenue_account_id"]) if fm.get("revenue_account_id") else None,
                    "tax_id": int(fm["tax_id"]) if fm.get("tax_id") else None,
                    "state": fm.get("state") or "active", "notes": fm.get("notes") or None}
            if vals["start_date"] and vals["end_date"] and vals["end_date"] < vals["start_date"]:
                raise AccountingError(t("The end date is before the start date."))
            members = [(int(u), r or None) for u, r in zip(fm.getlist("member_id"), fm.getlist("member_role")) if u]
            budget = []
            for acc, desc, amt in zip(fm.getlist("budget_account"), fm.getlist("budget_desc"), fm.getlist("budget_amount")):
                if acc or (amt or "").strip():
                    if not acc:
                        raise AccountingError(t("Every budget line needs an account."))
                    budget.append((int(acc), desc or None, to_int(amt or 0)))
            milestones = []
            for mid, name, amt, due in zip(fm.getlist("ms_id"), fm.getlist("ms_name"), fm.getlist("ms_amount"),
                                           fm.getlist("ms_due")):
                if (name or "").strip() or (amt or "").strip():
                    if not (name or "").strip():
                        raise AccountingError(t("Every milestone needs a name."))
                    milestones.append((int(mid) if mid else None, name.strip(), to_int(amt or 0), due or None))
            pid = pj.save_project(pid, vals, members, budget, milestones, user_id())
            commit()
            flash(t("Saved."), "success")
            return redirect(url_for("projects.view", pid=pid))
        except (AccountingError, ValueError) as e:
            get_db().rollback()
            flash(str(e), "error")
            p = dict(fm.items(), id=pid)
            members = [{"user_id": int(u) if u else None, "role": r} for u, r in zip(fm.getlist("member_id"),
                                                                                    fm.getlist("member_role"))]
            budget = [{"account_id": int(a) if a else None, "description": d, "amount": to_int(m or 0)}
                      for a, d, m in zip(fm.getlist("budget_account"), fm.getlist("budget_desc"),
                                         fm.getlist("budget_amount"))]
            milestones = [{"id": int(i) if i else None, "name": n, "amount": to_int(m or 0), "due_date": d}
                          for i, n, m, d in zip(fm.getlist("ms_id"), fm.getlist("ms_name"), fm.getlist("ms_amount"),
                                                fm.getlist("ms_due"))]
            return _render_form(p, members, budget, milestones)
    if p:
        return _render_form(p, [dict(m) for m in pj.members(pid)],
                            [dict(b) for b in q("SELECT * FROM project_budget WHERE project_id = ? ORDER BY id", (pid,))],
                            [dict(m, billed=pj.milestone_billed(m)) for m in
                             q("SELECT * FROM project_milestones WHERE project_id = ? ORDER BY sequence, id", (pid,))])
    nxt = q("SELECT COUNT(*) FROM projects", one=True)[0] + 1
    return _render_form({"code": f"PRJ-{nxt:03d}", "branch_id": default_branch(), "state": "active",
                         "budget_control": "warn", "retention_pct": 0, "start_date": date.today().isoformat()},
                        [], [], [])


def _render_form(p, members, budget, milestones):
    return render_template("projects/form.html", p=p, members=members, budget=budget, milestones=milestones,
                           branches=branch_map(), customers=partners_list("customer"), users=users_list(),
                           accounts=expense_accounts(), states=STATE_LABEL, controls=CONTROL_LABEL,
                           revenue_accounts=[a for a in q("SELECT * FROM accounts WHERE active = 1 AND is_group = 0 "
                                                          "ORDER BY code") if ROOT[a["kind"]] == "income"],
                           taxes=taxes_list("sale"))


def budget_export(p, rep_data):
    dec = currency_decimals(p["currency"])
    rep = Report("Project Budget Report", [f"{p['code']} — {nm(p)}", f"{t('Amounts in')} {p['currency']}",
                                           f"{t('As of')} {date.today().isoformat()}"], dec, landscape=True,
                 signatures=True)
    rep.column(t("Account"), width=2.2).column(t("Description"), width=1.6).column(t("Budget"), "num") \
        .column(t("Committed"), "num").column(t("Actual cost"), "num").column(t("Remaining"), "num") \
        .column(t("Used %"), "qty", 0.7)
    for r in rep_data["rows"]:
        rep.row([t(r["name_en"]) if r.get("unbudgeted") else f"{r['code']}  {nm(r)}", r["description"] or "",
                 r["budget"], r["committed"], r["actual"], r["remaining"],
                 r["used_pct"] if r["used_pct"] is not None else ""])
    tot = rep_data["total"]
    rep.row([t("Total"), "", tot["budget"], tot["committed"], tot["actual"], tot["remaining"],
             tot["used_pct"] if tot["used_pct"] is not None else ""], "grand")
    rep.notes.append(t("Committed = confirmed purchase orders not yet billed. Actual = costs posted to the project's "
                       "cost centre. Remaining = Budget − Committed − Actual."))
    return rep


@bp.route("/<int:pid>")
@login_required
def view(pid):
    p = get_project(pid)
    rep = pj.budget_report(pid)
    if request.args.get("export"):
        out = respond(budget_export(p, rep), f"{p['code']}-budget")
        if out:
            return out
    s = pj.summary(pid)
    milestones = [dict(m, billed=pj.milestone_billed(m), inv=q("SELECT number, state FROM invoices WHERE id = ?",
                                                                 (m["invoice_id"],), one=True) if m["invoice_id"] else None)
                  for m in q("SELECT * FROM project_milestones WHERE project_id = ? ORDER BY sequence, id", (pid,))]
    docs = {
        "mr": q("SELECT id, number, date, state FROM material_requests WHERE project_id = ? ORDER BY id DESC", (pid,)),
        "pr": q("SELECT id, number, date, state FROM purchase_requisitions WHERE project_id = ? ORDER BY id DESC", (pid,)),
        "rfq": q("SELECT id, number, date, state FROM rfqs WHERE project_id = ? ORDER BY id DESC", (pid,)),
        "po": q("SELECT o.id, o.number, o.date, o.state, o.kind, o.amount_untaxed, pa.name_en, pa.name_ar FROM orders o "
                "JOIN partners pa ON pa.id = o.partner_id WHERE o.project_id = ? ORDER BY o.id DESC", (pid,)),
        "inv": q("SELECT i.id, i.number, i.date, i.state, i.kind, i.amount_untaxed, i.amount_total, i.project_billing, "
                 "pa.name_en, pa.name_ar FROM invoices i JOIN partners pa ON pa.id = i.partner_id "
                 "WHERE i.project_id = ? ORDER BY i.date DESC, i.id DESC", (pid,)),
    }
    return render_template("projects/view.html", p=p, rep=rep, s=s, milestones=milestones, docs=docs,
                           members=pj.members(pid), states=STATE_LABEL, controls=CONTROL_LABEL,
                           today=date.today().isoformat())


@bp.route("/<int:pid>/milestone/<int:mid>/<action>", methods=["POST"])
@write_required
def milestone_action(pid, mid, action):
    get_project(pid)
    m = q("SELECT * FROM project_milestones WHERE id = ? AND project_id = ?", (mid, pid), one=True)
    if not m:
        abort(404)
    try:
        if action == "bill":
            inv_id = pj.bill_milestone(mid, request.form.get("date") or date.today().isoformat(), user_id())
            commit()
            flash(t("Draft progress invoice created. Check it and post it."), "success")
            return redirect(url_for("invoices.view", inv_id=inv_id))
        if action == "done" and m["state"] == "planned":
            x("UPDATE project_milestones SET state = 'done', completed_at = ? WHERE id = ?",
              (date.today().isoformat(), mid))
        elif action == "undo" and m["state"] == "done":
            x("UPDATE project_milestones SET state = 'planned', completed_at = NULL WHERE id = ?", (mid,))
        else:
            raise AccountingError(t("This action is not allowed in the current state."))
        audit(user_id(), f"milestone_{action}", "project", pid, m["name"])
        commit()
    except AccountingError as e:
        get_db().rollback()
        flash(str(e), "error")
    return redirect(url_for("projects.view", pid=pid) + "#milestones")


@bp.route("/<int:pid>/retention", methods=["POST"])
@write_required
def retention(pid):
    get_project(pid)
    try:
        amt = (request.form.get("amount") or "").strip()
        inv_id = pj.release_retention(pid, request.form.get("date") or date.today().isoformat(),
                                      to_int(amt) if amt else None, user_id())
        commit()
        flash(t("Draft retention release invoice created. Check it and post it."), "success")
        return redirect(url_for("invoices.view", inv_id=inv_id))
    except (AccountingError, ValueError) as e:
        get_db().rollback()
        flash(str(e), "error")
        return redirect(url_for("projects.view", pid=pid))


@bp.route("/<int:pid>/state", methods=["POST"])
@write_required
def set_state(pid):
    p = get_project(pid)
    new = request.form.get("state")
    if new not in STATE_LABEL:
        abort(400)
    x("UPDATE projects SET state = ? WHERE id = ?", (new, pid))
    pj.ensure_cost_centre(pid)
    audit(user_id(), f"state_{new}", "project", pid, p["code"])
    commit()
    flash(t("Saved."), "success")
    return redirect(url_for("projects.view", pid=pid))
