"""Fixed asset depreciation and prepaid / deferred / accrual recognition.

Both work the same way: a schedule of monthly lines (dated at month end) is generated when the document is
confirmed, and a period-end run posts every line due up to a date.

Asset entries          Dr Depreciation expense      Cr Accumulated depreciation
Prepaid expense        Dr Expense                   Cr Prepaid (asset)
Deferred revenue       Dr Deferred revenue          Cr Income
Accrual                Dr Expense                   Cr Accrued liability   (optionally reversed on the 1st)
"""
import calendar
from datetime import date, timedelta

from .db import placeholders, q, x
from .i18n import t
from .ledger import AccountingError, audit, create_move, now
from .money import round_cur
from .stock import stock_journal


def month_ends(start, n):
    d = date.fromisoformat(start)
    y, m = d.year, d.month
    out = []
    for _ in range(n):
        out.append(date(y, m, calendar.monthrange(y, m)[1]).isoformat())
        m += 1
        if m > 12:
            y, m = y + 1, 1
    return out


def branch_decimals(branch_id):
    return q("SELECT c.decimals FROM branches b JOIN currencies c ON c.code = b.currency WHERE b.id = ?",
             (branch_id,), one=True)["decimals"]


def acc_by_code(code):
    r = q("SELECT id FROM accounts WHERE code = ?", (code,), one=True)
    if not r:
        raise AccountingError(t("Missing account") + f" {code}")
    return r["id"]


# ---------------------------------------------------------------- assets

def depreciation_schedule(cost, salvage, start, life_months, method="linear", rate=0.0, decimals=2):
    """[(date, amount, accumulated, book_value)] in mils."""
    base = cost - salvage
    if base <= 0 or life_months <= 0:
        return []
    dates = month_ends(start, life_months)
    out = []
    acc = 0
    if method == "declining":
        annual = (rate or (200.0 / (life_months / 12.0))) / 100.0
    for i, d in enumerate(dates):
        left = base - acc
        remaining_months = life_months - i
        if i == life_months - 1:
            amt = left
        elif method == "declining":
            book = cost - acc
            amt = max(round_cur(int(book * annual / 12), decimals), round_cur(left // remaining_months, decimals))
            amt = min(amt, left)
        else:
            amt = round_cur(base // life_months, decimals)
        acc += amt
        out.append((d, amt, acc, cost - acc))
        if acc >= base:
            break
    return out


def confirm_asset(asset_id, user_id=None, acquisition_credit_account=None):
    a = q("SELECT * FROM assets WHERE id = ?", (asset_id,), one=True)
    if a["state"] != "draft":
        raise AccountingError(t("This action is not allowed in the current state."))
    cat = q("SELECT * FROM asset_categories WHERE id = ?", (a["category_id"],), one=True)
    if not (cat["asset_account_id"] and cat["depreciation_account_id"] and cat["expense_account_id"]):
        raise AccountingError(t("Set the accounts on the asset category."))
    if a["salvage"] >= a["cost"]:
        raise AccountingError(t("The salvage value must be lower than the cost."))
    x("DELETE FROM asset_lines WHERE asset_id = ?", (asset_id,))
    for d, amt, acc, bv in depreciation_schedule(a["cost"], a["salvage"], a["start_date"], a["life_months"],
                                                  a["method"], a["rate"], branch_decimals(a["branch_id"])):
        x("INSERT INTO asset_lines (asset_id, date, amount, accumulated, book_value) VALUES (?,?,?,?,?)",
          (asset_id, d, amt, acc, bv))
    if acquisition_credit_account:
        mid = create_move(a["branch_id"], stock_journal(a["branch_id"]), a["acquisition_date"], [
            {"account_id": cat["asset_account_id"], "partner_id": a["partner_id"], "label": a["name_en"],
             "debit": a["cost"], "credit": 0},
            {"account_id": int(acquisition_credit_account), "partner_id": a["partner_id"], "label": a["name_en"],
             "debit": 0, "credit": a["cost"]}], user_id=user_id, ref=a["code"], move_type="asset", post=True)
        x("UPDATE assets SET acquisition_move_id = ? WHERE id = ?", (mid, asset_id))
    x("UPDATE assets SET state = 'running' WHERE id = ?", (asset_id,))
    audit(user_id, "confirm", "asset", asset_id, a["code"])


def _post_asset_line(a, cat, line, user_id):
    mid = create_move(a["branch_id"], stock_journal(a["branch_id"]), line["date"], [
        {"account_id": cat["expense_account_id"], "label": f"{t('Depreciation')} {a['code']}", "debit": line["amount"],
         "credit": 0, "cost_centre_id": a["cost_centre_id"]},
        {"account_id": cat["depreciation_account_id"], "label": f"{t('Depreciation')} {a['code']}", "debit": 0,
         "credit": line["amount"]}], user_id=user_id, ref=a["code"], move_type="asset", post=True)
    x("UPDATE asset_lines SET move_id = ? WHERE id = ?", (mid, line["id"]))


def due_depreciation(up_to, branch_ids):
    if not branch_ids:
        return []
    return q(f"SELECT al.*, a.code, a.name_en, a.name_ar, a.branch_id FROM asset_lines al JOIN assets a ON a.id = al.asset_id "
             f"WHERE a.state = 'running' AND al.move_id IS NULL AND al.date <= ? AND a.branch_id IN "
             f"({placeholders(branch_ids)}) ORDER BY al.date, a.code", [up_to] + list(branch_ids))


def post_depreciation(up_to, branch_ids, user_id=None, asset_id=None):
    lines = due_depreciation(up_to, branch_ids)
    if asset_id:
        lines = [ln for ln in lines if ln["asset_id"] == asset_id]
    for ln in lines:
        a = q("SELECT * FROM assets WHERE id = ?", (ln["asset_id"],), one=True)
        cat = q("SELECT * FROM asset_categories WHERE id = ?", (a["category_id"],), one=True)
        _post_asset_line(a, cat, ln, user_id)
    for aid in {ln["asset_id"] for ln in lines}:
        if not q("SELECT 1 FROM asset_lines WHERE asset_id = ? AND move_id IS NULL", (aid,)):
            x("UPDATE assets SET state = 'closed' WHERE id = ?", (aid,))
    if lines:
        audit(user_id, "depreciation", "asset", None, f"{len(lines)} lines up to {up_to}")
    return len(lines)


def dispose_asset(asset_id, d, amount, proceeds_account_id, user_id=None):
    a = q("SELECT * FROM assets WHERE id = ?", (asset_id,), one=True)
    if a["state"] not in ("running", "closed"):
        raise AccountingError(t("This action is not allowed in the current state."))
    if amount and not proceeds_account_id:
        raise AccountingError(t("Choose the account that receives the sale proceeds."))
    post_depreciation(d, [a["branch_id"]], user_id, asset_id)
    x("DELETE FROM asset_lines WHERE asset_id = ? AND move_id IS NULL", (asset_id,))
    cat = q("SELECT * FROM asset_categories WHERE id = ?", (a["category_id"],), one=True)
    accumulated = q("SELECT COALESCE(SUM(amount), 0) FROM asset_lines WHERE asset_id = ?", (asset_id,), one=True)[0]
    nbv = a["cost"] - accumulated
    gain = amount - nbv
    label = f"{t('Disposal')} {a['code']}"
    lines = [{"account_id": cat["asset_account_id"], "label": label, "debit": 0, "credit": a["cost"]}]
    if accumulated:
        lines.append({"account_id": cat["depreciation_account_id"], "label": label, "debit": accumulated, "credit": 0})
    if amount:
        lines.append({"account_id": int(proceeds_account_id), "label": label, "debit": amount, "credit": 0})
    if gain > 0:
        lines.append({"account_id": acc_by_code("4910"), "label": label, "debit": 0, "credit": gain,
                      "cost_centre_id": a["cost_centre_id"]})
    elif gain < 0:
        lines.append({"account_id": acc_by_code("6910"), "label": label, "debit": -gain, "credit": 0,
                      "cost_centre_id": a["cost_centre_id"]})
    mid = create_move(a["branch_id"], stock_journal(a["branch_id"]), d, lines, user_id=user_id, ref=a["code"],
                      move_type="asset", post=True)
    x("UPDATE assets SET state = 'disposed', disposal_date = ?, disposal_amount = ?, disposal_move_id = ? WHERE id = ?",
      (d, amount, mid, asset_id))
    audit(user_id, "dispose", "asset", asset_id, f"{a['code']} gain {gain}")
    return mid


# ---------------------------------------------------------------- prepaid / deferred / accruals

KINDS = {
    "prepaid": {"label": "Prepaid Expense", "balance": "Prepaid account", "pl": "Expense account"},
    "deferred": {"label": "Deferred Revenue", "balance": "Deferred revenue account", "pl": "Income account"},
    "accrual": {"label": "Accrual", "balance": "Accrued liability account", "pl": "Expense account"},
}


def recognition_lines(total, start, months, decimals):
    dates = month_ends(start, months)
    per = round_cur(total // months, decimals)
    out = []
    left = total
    for i, d in enumerate(dates):
        amt = left if i == months - 1 else per
        out.append((d, amt))
        left -= amt
    return out


def confirm_schedule(sid, user_id=None):
    s = q("SELECT * FROM prepaid_schedules WHERE id = ?", (sid,), one=True)
    if s["state"] != "draft":
        raise AccountingError(t("This action is not allowed in the current state."))
    if s["total"] <= 0 or s["months"] <= 0:
        raise AccountingError(t("The amount must be greater than zero."))
    x("DELETE FROM prepaid_lines WHERE schedule_id = ?", (sid,))
    for d, amt in recognition_lines(s["total"], s["start_date"], s["months"], branch_decimals(s["branch_id"])):
        x("INSERT INTO prepaid_lines (schedule_id, date, amount) VALUES (?,?,?)", (sid, d, amt))
    x("UPDATE prepaid_schedules SET state = 'running' WHERE id = ?", (sid,))
    audit(user_id, "confirm", "prepaid", sid, s["number"])


def _entry_lines(s, amount, reverse=False):
    if s["kind"] == "deferred":
        dr, cr = s["balance_account_id"], s["pl_account_id"]
    else:  # prepaid and accrual both debit the P&L account
        dr, cr = s["pl_account_id"], s["balance_account_id"]
    if reverse:
        dr, cr = cr, dr
    label = s["name"] + (f" ({t('reversal')})" if reverse else "")
    cc = {s["pl_account_id"]: s["cost_centre_id"]}  # only the income / expense side is analysed
    return [{"account_id": dr, "partner_id": s["partner_id"], "label": label, "debit": amount, "credit": 0,
             "cost_centre_id": cc.get(dr)},
            {"account_id": cr, "partner_id": s["partner_id"], "label": label, "debit": 0, "credit": amount,
             "cost_centre_id": cc.get(cr)}]


def reversal_date(d):
    return (date.fromisoformat(d) + timedelta(days=1)).isoformat()


def due_recognitions(up_to, branch_ids):
    if not branch_ids:
        return [], []
    ph = placeholders(branch_ids)
    due = q(f"SELECT pl.*, s.number, s.name, s.kind, s.branch_id FROM prepaid_lines pl JOIN prepaid_schedules s "
            f"ON s.id = pl.schedule_id WHERE s.state = 'running' AND pl.move_id IS NULL AND pl.date <= ? "
            f"AND s.branch_id IN ({ph}) ORDER BY pl.date", [up_to] + list(branch_ids))
    rev = [r for r in q(f"SELECT pl.*, s.number, s.name, s.kind, s.branch_id FROM prepaid_lines pl JOIN prepaid_schedules s "
                        f"ON s.id = pl.schedule_id WHERE s.kind = 'accrual' AND s.auto_reverse = 1 AND s.state != 'cancelled' "
                        f"AND pl.move_id IS NOT NULL AND pl.reversal_move_id IS NULL AND s.branch_id IN ({ph}) "
                        f"ORDER BY pl.date", list(branch_ids))
           if reversal_date(r["date"]) <= up_to]
    return due, rev


def post_recognitions(up_to, branch_ids, user_id=None, schedule_id=None):
    due, rev = due_recognitions(up_to, branch_ids)
    if schedule_id:
        due = [r for r in due if r["schedule_id"] == schedule_id]
        rev = [r for r in rev if r["schedule_id"] == schedule_id]
    touched = set()
    for ln in due:
        s = q("SELECT * FROM prepaid_schedules WHERE id = ?", (ln["schedule_id"],), one=True)
        mid = create_move(s["branch_id"], stock_journal(s["branch_id"]), ln["date"], _entry_lines(s, ln["amount"]),
                          user_id=user_id, ref=s["number"], move_type="prepaid", partner_id=s["partner_id"], post=True)
        x("UPDATE prepaid_lines SET move_id = ? WHERE id = ?", (mid, ln["id"]))
        touched.add(s["id"])
    # reversals of accruals posted earlier in this run are picked up too
    _, rev = due_recognitions(up_to, branch_ids)
    if schedule_id:
        rev = [r for r in rev if r["schedule_id"] == schedule_id]
    for ln in rev:
        s = q("SELECT * FROM prepaid_schedules WHERE id = ?", (ln["schedule_id"],), one=True)
        mid = create_move(s["branch_id"], stock_journal(s["branch_id"]), reversal_date(ln["date"]),
                          _entry_lines(s, ln["amount"], reverse=True), user_id=user_id, ref=s["number"],
                          move_type="prepaid", partner_id=s["partner_id"], post=True)
        x("UPDATE prepaid_lines SET reversal_move_id = ? WHERE id = ?", (mid, ln["id"]))
        touched.add(s["id"])
    for sid in touched:
        s = q("SELECT * FROM prepaid_schedules WHERE id = ?", (sid,), one=True)
        pending = q("SELECT 1 FROM prepaid_lines WHERE schedule_id = ? AND (move_id IS NULL OR (? = 1 AND "
                    "reversal_move_id IS NULL))", (sid, 1 if s["kind"] == "accrual" and s["auto_reverse"] else 0))
        if not pending:
            x("UPDATE prepaid_schedules SET state = 'done' WHERE id = ?", (sid,))
    if due or rev:
        audit(user_id, "recognition", "prepaid", None, f"{len(due)} lines, {len(rev)} reversals up to {up_to}")
    return len(due), len(rev)
