"""Chart of accounts hierarchy: group (header) accounts and their sub-accounts.

A group account holds other accounts (posting accounts or more groups) and shows their total; nothing can be posted
to it. Every account may have a parent group, so the chart reads as a tree (1 Assets > 11 Current Assets > 111 Cash
and Bank > 1010 Cash on Hand). The statements still take their sections (current assets, revenue...) from the
account type; inside a section the accounts are nested under their groups, with the group total on the group line.
Groups that hold the whole section add nothing and are left out, so "Current Assets" is not repeated.
"""
from collections import defaultdict

from .db import q, x
from .i18n import nm, t
from .ledger import ROOT, AccountingError

# the standard grouped chart: (code, English, Arabic, type, parent code, account types it holds)
STANDARD = [
    ("1", "Assets", "الأصول", "asset_current", None, ()),
    ("11", "Current Assets", "الأصول المتداولة", "asset_current", "1", ()),
    ("111", "Cash and Bank", "النقد وما في حكمه", "asset_cash", "11", ("asset_cash",)),
    ("112", "Receivables", "الذمم المدينة", "asset_receivable", "11", ("asset_receivable",)),
    ("113", "Inventory and Other Current Assets", "المخزون والأصول المتداولة الأخرى", "asset_current", "11",
     ("asset_current",)),
    ("114", "Prepayments", "المصروفات المدفوعة مقدماً", "asset_prepayments", "11", ("asset_prepayments",)),
    ("12", "Non-current Assets", "الأصول غير المتداولة", "asset_fixed", "1", ()),
    ("121", "Property, Plant and Equipment", "الممتلكات والآلات والمعدات", "asset_fixed", "12", ("asset_fixed",)),
    ("122", "Other Non-current Assets", "أصول غير متداولة أخرى", "asset_non_current", "12", ("asset_non_current",)),
    ("2", "Liabilities", "الخصوم", "liability_current", None, ()),
    ("21", "Current Liabilities", "الخصوم المتداولة", "liability_current", "2", ()),
    ("211", "Payables", "الذمم الدائنة", "liability_payable", "21", ("liability_payable",)),
    ("212", "Other Current Liabilities", "خصوم متداولة أخرى", "liability_current", "21", ("liability_current",)),
    ("22", "Non-current Liabilities", "الخصوم غير المتداولة", "liability_non_current", "2",
     ("liability_non_current",)),
    ("3", "Equity", "حقوق الملكية", "equity", None, ("equity",)),
    ("4", "Revenue", "الإيرادات", "income", None, ()),
    ("41", "Operating Revenue", "إيرادات النشاط", "income", "4", ("income",)),
    ("42", "Other Income", "إيرادات أخرى", "income_other", "4", ("income_other",)),
    ("5", "Cost of Revenue", "تكلفة الإيرادات", "expense_direct_cost", None, ("expense_direct_cost",)),
    ("6", "Operating Expenses", "المصروفات التشغيلية", "expense", None, ()),
    ("61", "General and Administrative Expenses", "المصروفات العمومية والإدارية", "expense", "6", ("expense",)),
    ("62", "Depreciation", "الاستهلاك", "expense_depreciation", "6", ("expense_depreciation",)),
]


def has_groups():
    return bool(q("SELECT 1 FROM accounts WHERE is_group = 1 LIMIT 1", one=True))


def ungrouped():
    """Posting accounts that are not in any group yet."""
    return q("SELECT COUNT(*) FROM accounts WHERE is_group = 0 AND parent_id IS NULL", one=True)[0]


def auto_group():
    """Put every posting account without a group into the standard group for its type, creating the groups it
    needs. Accounts already in a group are left where they are. Returns the number of accounts grouped."""
    by_code = {r["code"]: r for r in q("SELECT * FROM accounts")}
    leaf = {k: g[0] for g in STANDARD for k in g[5]}
    parent = {g[0]: g[4] for g in STANDARD}
    todo = q("SELECT id, kind FROM accounts WHERE is_group = 0 AND parent_id IS NULL")
    needed = set()
    for a in todo:
        code = leaf.get(a["kind"])
        while code:
            needed.add(code)
            code = parent[code]
    ids = {}
    for code, en, ar, kind, par, _ in STANDARD:  # parents come before their children
        if code not in needed:
            continue
        ex = by_code.get(code)
        if ex and not ex["is_group"]:
            raise AccountingError(f"{t('The code')} {code} {t('is already used by a posting account.')}")
        if ex:
            ids[code] = ex["id"]
        else:
            ids[code] = x("INSERT INTO accounts (code, name_en, name_ar, kind, is_group, parent_id) VALUES (?,?,?,?,1,?)",
                          (code, en, ar, kind, ids.get(par)))
    for a in todo:
        if leaf.get(a["kind"]):
            x("UPDATE accounts SET parent_id = ? WHERE id = ?", (ids[leaf[a["kind"]]], a["id"]))
    return len(todo)


def children_map(accs):
    kids = defaultdict(list)
    for a in sorted(accs.values(), key=lambda a: a["code"]):
        kids[a["parent_id"]].append(a)
    return kids


def ancestors(acc, accs):
    """Groups above an account, top first."""
    chain, seen = [], set()
    p = acc["parent_id"]
    while p and p in accs and p not in seen:
        seen.add(p)
        chain.append(accs[p])
        p = accs[p]["parent_id"]
    return chain[::-1]


def tree(accs):
    """[(account, depth)] in chart order, depth 1 at the top."""
    kids, out = children_map(accs), []

    def walk(pid, depth):
        for a in kids.get(pid, []):
            out.append((a, depth))
            walk(a["id"], depth + 1)
    walk(None, 1)
    # accounts whose parent is missing (should not happen) still appear
    shown = {a["id"] for a, _ in out}
    out += [(a, 1) for a in accs.values() if a["id"] not in shown]
    return out


def max_depth():
    accs = {a["id"]: a for a in q("SELECT id, parent_id FROM accounts")}
    return max((len(ancestors(a, accs)) + 1 for a in accs.values()), default=1)


def check_account(values, key, accs):
    """Rules for saving an account from the chart of accounts form."""
    me = int(key) if key is not None else None
    pid = int(values["parent_id"]) if values.get("parent_id") else None
    if pid:
        par = accs.get(pid)
        if not par or not par["is_group"]:
            raise AccountingError(t("The parent must be a group account."))
        if me and (pid == me or me in [a["id"] for a in ancestors(par, accs)]):
            raise AccountingError(t("An account cannot be placed under itself or one of its own sub-accounts."))
        if ROOT[par["kind"]] != ROOT[values["kind"]]:
            raise AccountingError(t("The account type does not match its group (for example an expense under "
                                    "assets)."))
    if me is None:
        return
    if values.get("is_group"):
        if q("SELECT 1 FROM move_lines WHERE account_id = ? LIMIT 1", (me,), one=True):
            raise AccountingError(t("This account already has entries, so it cannot become a group. Create a new "
                                    "group and put this account under it."))
    elif any(a["parent_id"] == me for a in accs.values()):
        raise AccountingError(t("This group still has accounts under it. Move them first."))
    for a in accs.values():
        if a["parent_id"] == me and ROOT[a["kind"]] != ROOT[values["kind"]]:
            raise AccountingError(t("The account type does not match the accounts under this group."))


def nest(rows, sums, level=None, finish=None, accs=None):
    """Nest runs of account rows under their group accounts.

    rows: report rows; a row with an "account" is nested, other rows (sections, subtotals) stay where they are.
    sums: the keys added up on group lines (a list value is added item by item).
    level: show only the first n levels (None: everything); hidden accounts are still in their group's total.
    finish: called on each new group row to fill derived figures (percentages...)."""
    accs = accs or {a["id"]: a for a in q("SELECT * FROM accounts")}
    if not any(a["is_group"] for a in accs.values()) and not level:
        return rows
    out, run = [], []

    def flush():
        if run:
            out.extend(_nest_run(run, sums, level, finish, accs))
            run.clear()
    for r in rows:
        if r.get("account"):
            run.append(r)
        else:
            flush()
            out.append(r)
    flush()
    return out


def _add(a, b):
    if isinstance(a, list):
        return [x + y for x, y in zip(a, b)]
    return a + b


def _nest_run(run, sums, level, finish, accs):
    root = {"children": {}, "rows": []}
    for r in run:
        node = root
        for g in ancestors(r["account"], accs):
            node = node["children"].setdefault(g["id"], {"group": g, "children": {}, "rows": []})
        node["rows"].append(r)
    # a group that holds every account of the run repeats the section heading; leave it out
    while len(root["children"]) == 1 and not root["rows"]:
        root = next(iter(root["children"].values()))
    out = []

    def total(node):
        vals = None
        for r in node["rows"]:
            vals = {k: r[k] for k in sums} if vals is None else {k: _add(vals[k], r[k]) for k in sums}
        for c in node["children"].values():
            sub = total(c)
            vals = sub if vals is None else {k: _add(vals[k], sub[k]) for k in sums}
        return vals

    def walk(node, depth):
        items = [("g", c["group"]["code"], c) for c in node["children"].values()] + \
                [("a", r["account"]["code"], r) for r in node["rows"]]
        for typ, _code, item in sorted(items, key=lambda i: i[1]):
            if level and depth > level:
                return
            if typ == "a":
                out.append({**item, "depth": depth})
                continue
            g = item["group"]
            row = {"label": f"{g['code']} {nm(g)}", "kind": "group", "account": None, "group": g, "depth": depth,
                   "level": run[0].get("level", 1), **total(item)}
            if finish:
                finish(row)
            out.append(row)
            walk(item, depth + 1)
    walk(root, 1)
    return out


def parse_level(v):
    return int(v) if v and str(v).isdigit() and int(v) > 0 else None
