"""Licensed modules. Each customer installation has instance/license.json, signed by the vendor
with `python manage.py license ...`. Without a license file every module is enabled (development)."""
import hashlib
import hmac
import json
import os
from datetime import date

MODULES = {
    "accounting": {"name": "Accounting", "name_ar": "المحاسبة", "core": True, "requires": [],
                   "desc": "Chart of accounts, journal entries, invoices, payments, multi-branch, consolidation, reports"},
    "sales": {"name": "Sales", "name_ar": "المبيعات", "requires": ["accounting"],
              "desc": "Quotations, sales orders, delivery and invoicing from orders"},
    "procurement": {"name": "Procurement", "name_ar": "المشتريات", "requires": ["accounting"],
                    "desc": "Material requests, purchase requisitions, RFQs with comparison, purchase orders, approvals"},
    "vendors": {"name": "Vendor Management", "name_ar": "إدارة الموردين", "requires": ["accounting"],
                "desc": "Vendor onboarding and approval, documents with expiry, evaluations and scorecards"},
    "inventory": {"name": "Inventory", "name_ar": "المخزون", "requires": ["accounting"],
                  "desc": "Warehouses, stock on hand, receipts, deliveries, adjustments, average costing"},
    "assets": {"name": "Fixed Assets", "name_ar": "الأصول الثابتة", "requires": ["accounting"],
               "desc": "Asset register, depreciation schedules, monthly posting, disposal"},
    "crm": {"name": "CRM", "name_ar": "إدارة علاقات العملاء", "requires": ["accounting"],
            "desc": "Leads and opportunities pipeline, activities, win/loss analysis, quotations from leads"},
    "pos": {"name": "Point of Sale", "name_ar": "نقاط البيع", "requires": ["accounting"],
            "desc": "Cashier sessions, touch selling screen, cash/card payments, refunds, receipts, automatic posting"},
    "bank": {"name": "Bank Reconciliation", "name_ar": "التسويات البنكية", "requires": ["accounting"],
             "desc": "Bank statement import, matching and auto-matching, bank reconciliation statement"},
    "prepaid": {"name": "Prepaid & Accruals", "name_ar": "المدفوعات المقدمة والمستحقات", "requires": ["accounting"],
                "desc": "Prepaid expenses, deferred revenue, accruals with automatic reversal"},
    "hr": {"name": "HR & Payroll", "name_ar": "الموارد البشرية والرواتب", "requires": ["accounting"],
           "desc": "Employees, monthly payroll with GOSI and WPS file, leave, loans, end-of-service benefits"},
    "projects": {"name": "Projects", "name_ar": "المشاريع", "requires": ["accounting"],
                 "desc": "Projects with manager and team, budgets, committed and actual cost, progress billing, retention"},
    "portal": {"name": "Supplier Portal", "name_ar": "بوابة الموردين", "requires": ["vendors"],
               "desc": "Supplier registration link, onboarding approval, vendor portal logins with activation links"},
}

# What each kind of business uses. Within its license a company switches on only its own modules, so a trading
# shop never sees projects or retention, and a contractor never sees the cash register.
BUSINESS_TYPES = {
    "trading": {"name": "Trading / distribution / retail", "name_ar": "تجارة / توزيع / تجزئة",
                "modules": ["accounting", "sales", "procurement", "vendors", "portal", "inventory", "pos", "crm", "bank",
                            "assets", "prepaid", "hr"],
                "desc": "Buy and sell goods: stock, warehouses, POS, purchasing, customers and suppliers."},
    "contracting": {"name": "Contracting / construction", "name_ar": "مقاولات / إنشاءات",
                    "modules": ["accounting", "sales", "procurement", "vendors", "portal", "inventory", "projects", "bank",
                                "assets", "prepaid", "hr"],
                    "desc": "Projects with budgets, site material requests, subcontractors, progress billing and retention."},
    "services": {"name": "Services / consulting", "name_ar": "خدمات / استشارات",
                 "modules": ["accounting", "sales", "crm", "projects", "bank", "assets", "prepaid", "hr"],
                 "desc": "Client work and projects, time-based billing, no stock."},
    "custom": {"name": "Custom (choose the modules)", "name_ar": "مخصص (اختر الوحدات)", "modules": None,
               "desc": "Any combination of the licensed modules."},
}

DEV_SECRET = "vertex-development-secret"


def secret():
    return os.environ.get("VERTEX_LICENSE_SECRET", DEV_SECRET).encode()


def _payload(lic):
    body = {k: v for k, v in lic.items() if k != "signature"}
    return json.dumps(body, sort_keys=True, ensure_ascii=False).encode()


def sign(lic):
    return hmac.new(secret(), _payload(lic), hashlib.sha256).hexdigest()


def make_license(licensee, modules, max_users=0, max_branches=0, expires=None):
    mods = set(modules) | {"accounting"}
    for m in list(mods):
        if m not in MODULES:
            raise ValueError(f"Unknown module: {m}")
        mods |= set(MODULES[m]["requires"])
    lic = {"licensee": licensee, "modules": sorted(mods), "max_users": max_users or 0,
           "max_branches": max_branches or 0, "expires": expires, "issued": date.today().isoformat()}
    lic["signature"] = sign(lic)
    return lic


class License:
    def __init__(self, path):
        self.path = path
        self.data = None
        self.valid = True
        self.error = None
        if os.path.exists(path):
            try:
                with open(path, encoding="utf-8") as f:
                    self.data = json.load(f)
                if not hmac.compare_digest(self.data.get("signature", ""), sign(self.data)):
                    self.valid, self.error = False, "License signature is invalid."
            except (OSError, ValueError) as e:
                self.valid, self.error = False, f"License file cannot be read: {e}"

    @property
    def licensed(self):
        return self.data is not None

    @property
    def modules(self):
        if not self.licensed:
            return set(MODULES)
        if not self.valid:
            return {"accounting"}
        return set(self.data.get("modules", [])) | {"accounting"}

    @property
    def expired(self):
        exp = self.data and self.data.get("expires")
        return bool(exp) and date.today().isoformat() > exp

    @property
    def read_only(self):
        return self.licensed and (not self.valid or self.expired)

    def limit(self, key):
        return (self.data or {}).get(key) or 0


def sync_module_accounts(enabled):
    """Accounts that only one kind of business uses follow its module: the retention receivable is hidden from the
    account lists when Projects is off (never while it still carries a balance) and shown again when it is on."""
    from .db import q, x
    row = q("SELECT retention_account_id FROM company WHERE id = 1", one=True)
    acc = row["retention_account_id"] if row else None
    if not acc:
        return
    if enabled is None or "projects" in enabled:
        x("UPDATE accounts SET active = 1 WHERE id = ?", (acc,))
    elif not q("SELECT 1 FROM move_lines WHERE account_id = ? LIMIT 1", (acc,), one=True):
        x("UPDATE accounts SET active = 0 WHERE id = ?", (acc,))
