"""Apps shown as tiles on the home screen. Each app has its own menu, shown in the sidebar while you work in it.

An item is (endpoint, label, icon, url args, condition). Conditions: a module key (licensed), "admin", "write",
or a tuple of them (all must hold). An app needs its module licensed and at least one visible item.
"""
from flask import g, request, session, url_for

APPS = [
    # key, label, icon, colour, home group, module, menu sections [(section label or None, items)]
    ("sales", "Sales", "trend", "#2563eb", "Operations", None, [
        (None, [("insights.sales", "Overview", "chart", {}, None),
                ("invoices.index", "Customer Invoices", "receipt", {"kind": "out_invoice"}, None),
                ("orders.index", "Quotations & Orders", "file", {"kind": "sale"}, "sales"),
                ("invoices.index", "Proforma Invoices", "file", {"kind": "out_invoice", "type": "proforma"}, None),
                ("invoices.index", "Credit Notes", "undo", {"kind": "out_refund"}, None),
                ("invoices.advances", "Customer Advances", "coins", {}, None),
                ("payments.index", "Customer Payments", "wallet", {"partner_type": "customer"}, None),
                ("cheques.index", "Cheques Received", "receipt", {"direction": "received"}, None),
                ("statements.index", "Customer Statements", "mail", {"side": "customer"}, None),
                ("recurring.index", "Recurring Invoices", "refresh", {"kind": "out_invoice"}, None),
                ("credit.index", "Credit Control", "shield", {}, None),
                ("inventory.pickings", "Deliveries", "truck", {"kind": "out"}, "inventory")]),
        ("Setup", [("setup.list_view", "Customers", "users", {"model": "partners", "type": "customer"}, None),
                   ("setup.list_view", "Products", "tag", {"model": "products"}, None)]),
        ("Reports", [("reports.partner_ledger", "Customer Ledger", "ledger", {"side": "customer"}, None),
                     ("reports.sales", "Sales Analysis", "chart", {}, None),
                     ("insights.margin", "Gross Margin", "percent", {}, None),
                     ("reports.aged", "Aged Receivables", "clock", {"side": "receivable"}, None)]),
    ]),
    ("purchases", "Purchases", "cart", "#d97706", "Operations", None, [
        (None, [("insights.purchases", "Overview", "chart", {}, None),
                ("orders.index", "Purchase Orders", "cart", {"kind": "purchase"}, "procurement"),
                ("invoices.index", "Vendor Bills", "file-in", {"kind": "in_invoice"}, None),
                ("vendors.ap_inbox", "AP Inbox", "down", {}, "portal"),
                ("invoices.index", "Vendor Refunds", "undo", {"kind": "in_refund"}, None),
                ("payments.index", "Vendor Payments", "wallet", {"partner_type": "vendor"}, None),
                ("cheques.index", "Cheques Issued", "receipt", {"direction": "issued"}, None),
                ("statements.index", "Vendor Statements", "mail", {"side": "vendor"}, None),
                ("recurring.index", "Recurring Bills", "refresh", {"kind": "in_invoice"}, None),
                ("inventory.pickings", "Receipts", "down", {"kind": "in"}, "inventory"),
                ("inventory.reorder", "Reorder Suggestions", "refresh", {}, "inventory")]),
        ("Procurement", [("procurement.mr_list", "Material Requests", "clipboard", {}, "procurement"),
                         ("procurement.pr_list", "Purchase Requisitions", "list", {}, "procurement"),
                         ("procurement.rfq_list", "Requests for Quotation", "mail", {}, "procurement")]),
        ("Setup", [("setup.list_view", "Vendors", "building", {"model": "partners", "type": "vendor"}, None),
                   ("setup.list_view", "Products", "tag", {"model": "products"}, None)]),
        ("Reports", [("reports.partner_ledger", "Vendor Ledger", "ledger", {"side": "vendor"}, None),
                     ("reports.aged", "Aged Payables", "clock", {"side": "payable"}, None),
                     ("insights.suppliers", "Supplier Performance", "target", {}, None),
                     ("insights.forecast", "13-Week Cash Forecast", "wallet", {}, None)]),
    ]),
    ("inventory", "Inventory", "box", "#0d9488", "Operations", "inventory", [
        (None, [("insights.inventory", "Overview", "chart", {}, None),
                ("inventory.stock", "Stock on Hand", "box", {}, None),
                ("inventory.pickings", "Receipts", "down", {"kind": "in"}, None),
                ("inventory.pickings", "Deliveries", "truck", {"kind": "out"}, None),
                ("inventory.pickings", "Customer Returns", "undo", {"kind": "return_in"}, None),
                ("inventory.pickings", "Vendor Returns", "refresh", {"kind": "return_out"}, None),
                ("wtransfers.index", "Warehouse Transfers", "shuffle", {}, None),
                ("inventory.landed_costs", "Landed Costs", "coins", {}, None),
                ("inventory.pickings", "Adjustments", "sliders", {"kind": "adjust"}, None),
                ("inventory.pickings", "Write-offs", "alert", {"kind": "scrap"}, None),
                ("inventory.batches", "Batches & Expiry", "clock", {}, None),
                ("inventory.reorder", "Reorder Suggestions", "refresh", {}, None),
                ("inventory.labels", "Print Labels", "tag", {}, None),
                ("inventory.moves", "Stock Moves", "shuffle", {}, None)]),
        ("Setup", [("setup.list_view", "Products", "tag", {"model": "products"}, None),
                   ("setup.list_view", "Product Categories", "layers", {"model": "product_categories"}, None),
                   ("setup.list_view", "Warehouses", "box", {"model": "warehouses"}, "admin")]),
        ("Reports", [("reports.stock_matching", "Stock vs Invoices", "swap", {}, None),
                     ("insights.margin", "Gross Margin", "percent", {"by": "product"}, None)]),
    ]),
    ("pos", "Point of Sale", "monitor", "#7c3aed", "Operations", "pos", [
        (None, [("pos.index", "Point of Sale", "monitor", {}, None),
                ("setup.list_view", "Products", "tag", {"model": "products"}, None),
                ("setup.list_view", "Customers", "users", {"model": "partners", "type": "customer"}, None)]),
    ]),
    ("crm", "CRM", "target", "#db2777", "Operations", "crm", [
        (None, [("crm.pipeline", "Pipeline", "target", {}, None),
                ("crm.leads", "Leads", "list", {}, None),
                ("crm.activities", "My Activities", "check", {}, None),
                ("setup.list_view", "Customers", "users", {"model": "partners", "type": "customer"}, None)]),
        ("Reports", [("crm.report", "CRM Report", "chart", {}, None)]),
    ]),
    ("vendors", "Vendors", "building", "#475569", "Operations", "vendors", [
        (None, [("vendors.index", "Vendor Management", "building", {}, None),
                ("vendors.registrations", "Supplier Registrations", "clipboard", {}, "portal"),
                ("vendors.ap_inbox", "AP Inbox", "file-in", {}, "portal"),
                ("vendors.bank_changes", "Bank Detail Changes", "bank", {}, None),
                ("vendors.expiring", "Vendor Documents", "file", {}, None)]),
    ]),
    ("accounting", "Accounting", "book", "#4f46e5", "Finance", None, [
        (None, [("entries.index", "Journal Entries", "book", {}, None),
                ("transfers.index", "Inter-branch Transfers", "swap", {}, None),
                ("pettycash.index", "Petty Cash", "wallet", {}, None),
                ("recurring.index", "Recurring Documents", "refresh", {}, None),
                ("budgets.index", "Budgets", "target", {}, None),
                ("fx.index", "Currency Revaluation", "coins", {}, None),
                ("closing.index", "Month-end Closing", "lock", {}, "write")]),
        ("Setup", [("setup.list_view", "Chart of Accounts", "layers", {"model": "accounts"}, None),
                   ("setup.list_view", "Cost Centres", "target", {"model": "cost_centres"}, None),
                   ("setup.list_view", "Journals", "book", {"model": "journals"}, "admin"),
                   ("setup.list_view", "Taxes", "percent", {"model": "taxes"}, "admin"),
                   ("setup.list_view", "Currencies", "coins", {"model": "currencies"}, "admin"),
                   ("setup.list_view", "Exchange Rates", "refresh", {"model": "rates"}, "admin")]),
        ("Reports", [("reports.gl", "General Ledger", "ledger", {}, None),
                     ("reports.tb", "Trial Balance", "grid", {}, None),
                     ("reports.pl_cost_centre", "P&L by Cost Centre", "target", {}, None),
                     ("budgets.report", "Budget vs Actual", "chart", {}, None)]),
    ]),
    ("bank", "Bank", "bank", "#0891b2", "Finance", "bank", [
        (None, [("bank.index", "Bank Reconciliation", "bank", {}, None),
                ("cheques.index", "Cheques Received", "receipt", {"direction": "received"}, None),
                ("cheques.index", "Cheques Issued", "receipt", {"direction": "issued"}, None),
                ("payments.index", "Customer Payments", "wallet", {"partner_type": "customer"}, None),
                ("payments.index", "Vendor Payments", "wallet", {"partner_type": "vendor"}, None)]),
        ("Reports", [("bank.report", "Reconciliation Report", "chart", {}, None)]),
    ]),
    ("assets", "Fixed Assets", "asset", "#b45309", "Finance", "assets", [
        (None, [("assets.index", "Fixed Assets", "asset", {}, None)]),
        ("Setup", [("setup.list_view", "Asset Categories", "layers", {"model": "asset_categories"}, "admin")]),
    ]),
    ("prepaid", "Prepaid & Accruals", "calendar", "#0d9488", "Finance", "prepaid", [
        (None, [("prepaid.index", "Prepaid & Accruals", "calendar", {}, None)]),
    ]),
    ("reports", "Reports", "chart", "#4f46e5", "Finance", None, [
        ("Financial statements", [("reports.pl", "Profit & Loss", "trend", {}, None),
                                  ("reports.pl_cost_centre", "P&L by Cost Centre", "target", {}, None),
                                  ("budgets.report", "Budget vs Actual", "chart", {}, None),
                                  ("reports.bs", "Balance Sheet", "scale", {}, None),
                                  ("reports.cf", "Cash Flow Statement", "wallet", {}, None),
                                  ("insights.forecast", "13-Week Cash Forecast", "calendar", {}, None),
                                  ("reports.tb", "Trial Balance", "grid", {}, None),
                                  ("reports.gl", "General Ledger", "ledger", {}, None)]),
        ("Partners", [("reports.partner_ledger", "Partner Ledger", "ledger", {"side": "all"}, None),
                      ("reports.aged", "Aged Receivables", "clock", {"side": "receivable"}, None),
                      ("reports.aged", "Aged Payables", "clock", {"side": "payable"}, None),
                      ("statements.index", "Customer Statements", "mail", {"side": "customer"}, None),
                      ("statements.index", "Vendor Statements", "mail", {"side": "vendor"}, None)]),
        ("Tax and sales", [("reports.vat", "VAT Report", "percent", {}, None),
                           ("reports.sales", "Sales Analysis", "chart", {}, None),
                           ("insights.margin", "Gross Margin", "percent", {}, None),
                           ("reports.stock_matching", "Stock vs Invoices", "swap", {}, "inventory")]),
    ]),
    ("dashboard", "Dashboard", "home", "#2563eb", "Finance", None, [
        (None, [("dashboard.index", "Dashboard", "home", {}, None),
                ("reports.pl", "Profit & Loss", "trend", {}, None),
                ("reports.bs", "Balance Sheet", "scale", {}, None),
                ("reports.cf", "Cash Flow Statement", "wallet", {}, None)]),
    ]),
    ("projects", "Projects", "briefcase", "#0f766e", "Operations", "projects", [
        (None, [("projects.index", "Projects", "briefcase", {}, None),
                ("procurement.mr_list", "Material Requests", "clipboard", {}, "procurement"),
                ("orders.index", "Purchase Orders", "cart", {"kind": "purchase"}, "procurement")]),
    ]),
    ("hr", "HR & Payroll", "users", "#be185d", "Operations", "hr", [
        (None, [("hr.employees", "Employees", "users", {}, None),
                ("hr.payroll", "Payroll", "wallet", {}, None),
                ("hr.leave", "Leave", "calendar", {}, None),
                ("hr.loans", "Loans & Advances", "coins", {}, None),
                ("hr.settlements", "Final Settlements", "file", {}, None)]),
        ("Reports", [("hr.provisions", "End of Service & Leave", "scale", {}, None),
                     ("hr.documents", "Expiring Documents", "clock", {}, None)]),
        ("Setup", [("hr.hr_settings", "HR Settings", "settings", {}, "admin")]),
    ]),
    ("settings", "Settings", "settings", "#475569", "Administration", None, [
        (None, [("setup.company_view", "Company", "building", {}, "admin"),
                ("setup.list_view", "Branches", "branch", {"model": "branches"}, "admin"),
                ("setup.list_view", "Warehouses", "box", {"model": "warehouses"}, ("admin", "inventory")),
                ("setup.users", "Users", "users", {}, "super"),
                ("setup.license_view", "License & Modules", "key", {}, "admin"),
                ("workflow.rules", "Approval Workflow", "check", {}, "admin"),
                ("workflow.roles", "Approval Roles", "users", {}, "admin"),
                ("workflow.terms", "Terms & Conditions", "file", {}, "admin"),
                ("setup.backups", "Backups", "history", {}, "perm:backup"),
                ("setup.access", "Provider Access", "key", {}, "superadmin"),
                ("code.index", "Code Editor", "file", {}, "superadmin"),
                ("setup.email_log", "Email Log", "mail", {}, "admin"),
                ("setup.audit_log", "Audit Log", "history", {}, "admin")]),
        ("Accounting setup", [("setup.list_view", "Journals", "book", {"model": "journals"}, "admin"),
                              ("setup.list_view", "Taxes", "percent", {"model": "taxes"}, "admin"),
                              ("setup.list_view", "Currencies", "coins", {"model": "currencies"}, "admin"),
                              ("setup.list_view", "Exchange Rates", "refresh", {"model": "rates"}, "admin")]),
    ]),
    ("import", "Data Import", "upload", "#475569", "Administration", None, [
        (None, [("imports.index", "Data Import", "upload", {}, "admin")]),
    ]),
]

GROUPS = ["Operations", "Finance", "Administration"]


def _ok(cond):
    from . import has
    if not cond:
        return True
    if isinstance(cond, tuple):
        return all(_ok(c) for c in cond)
    role = g.user["role"]
    if cond == "admin":
        return role == "admin"
    from . import can, is_prime, is_super
    if cond == "superadmin":
        return is_prime()
    if cond == "super":
        return is_super()
    if isinstance(cond, str) and cond.startswith("perm:"):
        return can(cond[5:])
    if cond == "write":
        return role in ("admin", "accountant")
    return has(cond)


def visible_apps():
    """Apps this user can open, with their menus resolved to URLs: [{key, label, icon, color, group, sections}]."""
    from . import has
    out = []
    for key, label, icon, color, group, module, sections in APPS:
        if module and not has(module):
            continue
        secs = []
        for sec_label, items in sections:
            links = [{"url": url_for(ep, **args), "label": lbl, "icon": ic}
                     for ep, lbl, ic, args, cond in items if _ok(cond)]
            if links:
                secs.append({"label": sec_label, "links": links})
        if secs:
            out.append({"key": key, "label": label, "icon": icon, "color": color, "group": group, "sections": secs,
                        "url": secs[0]["links"][0]["url"]})
    return out


def locked_apps():
    """Apps whose module is not in the license (offered on the home screen)."""
    from . import has
    return [{"key": key, "label": label, "icon": icon, "color": color}
            for key, label, icon, color, group, module, _ in APPS if module and not has(module)]


# blueprint -> app, for pages that are not in any menu (a document opened from a list or a link)
BLUEPRINT_APP = {"credit": "sales", "entries": "accounting", "budgets": "accounting", "transfers": "accounting", "closing": "accounting", "inventory": "inventory",
                 "assets": "assets", "prepaid": "prepaid", "bank": "bank", "crm": "crm", "pos": "pos",
                 "vendors": "vendors", "procurement": "purchases", "reports": "reports", "imports": "import",
                 "dashboard": "dashboard", "insights": "reports", "hr": "hr", "fx": "accounting", "pettycash": "accounting", "wtransfers": "inventory", "workflow": "settings", "projects": "projects"}


def page_hint():
    """The app a page belongs to judging by its blueprint and, for invoices, orders and payments, by the document."""
    from .db import q
    bp, args = request.blueprint, request.view_args or {}
    if bp == "invoices":
        kind = args.get("kind")
        if not kind and args.get("inv_id"):
            r = q("SELECT kind FROM invoices WHERE id = ?", (args["inv_id"],), one=True)
            kind = r and r["kind"]
        return "purchases" if kind and kind.startswith("in_") else "sales" if kind else None
    if bp == "orders":
        kind = args.get("kind")
        if not kind and args.get("order_id"):
            r = q("SELECT kind FROM orders WHERE id = ?", (args["order_id"],), one=True)
            kind = r and r["kind"]
        return "purchases" if kind == "purchase" else "sales" if kind else None
    if bp == "payments":
        ptype = request.args.get("partner_type")
        if not ptype and args.get("pid"):
            r = q("SELECT partner_type FROM payments WHERE id = ?", (args["pid"],), one=True)
            ptype = r and r["partner_type"]
        return "purchases" if ptype == "vendor" else "sales" if ptype else None
    if bp == "recurring":
        kind = request.args.get("kind")
        if not kind and args.get("rid"):
            r = q("SELECT kind FROM recurring WHERE id = ?", (args["rid"],), one=True)
            kind = r and r["kind"]
        if not kind and request.args.get("from_invoice", "").isdigit():
            r = q("SELECT kind FROM invoices WHERE id = ?", (request.args["from_invoice"],), one=True)
            kind = r and r["kind"]
        return {"out_invoice": "sales", "in_invoice": "purchases"}.get(kind, "accounting")
    if bp == "cheques":
        direction = args.get("direction")
        if not direction and args.get("cid"):
            r = q("SELECT direction FROM cheques WHERE id = ?", (args["cid"],), one=True)
            direction = r and r["direction"]
        return "purchases" if direction == "issued" else "sales"
    if bp == "statements":
        return "purchases" if args.get("side") == "vendor" else "sales"
    if bp == "setup":
        model = args.get("model")
        return "inventory" if model in ("products", "product_categories", "warehouses") else \
            "accounting" if model == "accounts" else "settings"
    return BLUEPRINT_APP.get(bp)


def current_app(apps):
    """The app the current page belongs to: the one whose menu has this page (preferring the app last opened),
    else the app its document belongs to, else the app last opened."""
    full, path = request.full_path.rstrip("?"), request.path
    last = session.get("app")
    for exact in (True, False):
        hits = [a["key"] for a in apps for s in a["sections"] for ln in s["links"]
                if (ln["url"] == full if exact else ln["url"].split("?")[0] == path)]
        if hits:
            key = last if last in hits else hits[0]
            session["app"] = key
            return key
    keys = [a["key"] for a in apps]
    hint = page_hint()
    if hint in keys:
        session["app"] = hint
        return hint
    return last if last in keys else (keys[0] if keys else None)
