import json
import os
from copy import deepcopy
from flask import current_app


DEFAULT_SETTINGS = {
    "company": {
        "app_name": "Jana ERP",
        "company_name": "Jana",
        "logo_url": "",
        "support_email": "",
        "primary_color": "#1f2937",
        "footer_text": "You are receiving this email because you have an account.",
    },
    "email": {
        "cc_admin": True,
    },
    "access": {
        # real access control matrix used by backend + frontend
        # actions: view/create/update/delete
        # resources: pages and APIs share the same keys for simplicity
        "roles": {
            "member": {
                "home.view": True,
                "profile.view": True,
                "notifications.view": True,
                "settings.view": True,
                "reports.view": True,
                "credits.view": True,
                "credits.create": False,
                "credits.update": False,
                "credits.delete": False,
                "debits.view": True,
                "debits.create": False,
                "debits.update": False,
                "debits.delete": False,
                "requests.submit": True,
                "requests.view_all": True,
                "admin.overview.view": False,
                "admin.member_savings.view": False,
                "admin.cashier_analysis.view": False,
            },
            "editor": {
                "home.view": True,
                "profile.view": True,
                "notifications.view": True,
                "settings.view": True,
                "reports.view": True,
                "cashier_summary.view": True,
                "credits.view": True,
                "credits.create": True,
                "credits.update": True,
                "credits.delete": True,
                "debits.view": True,
                "debits.create": True,
                "debits.update": True,
                "debits.delete": True,
                "requests.submit": True,
                "requests.view_all": False,
                "admin.overview.view": True,
                "admin.member_savings.view": True,
                "admin.cashier_analysis.view": True,
            },
            "administrator": {
                "*": True,
            },
        }
    },
}


def _ensure_parent_dir(path: str) -> None:
    os.makedirs(os.path.dirname(path), exist_ok=True)


def load_settings() -> dict:
    path = current_app.config.get("SETTINGS_FILE")
    if not path:
        return deepcopy(DEFAULT_SETTINGS)
    try:
        if not os.path.exists(path):
            return deepcopy(DEFAULT_SETTINGS)
        with open(path, "r", encoding="utf-8") as f:
            data = json.load(f) or {}
        merged = deepcopy(DEFAULT_SETTINGS)
        merged["company"].update(data.get("company", {}) or {})
        merged["email"].update(data.get("email", {}) or {})
        merged["access"].update(data.get("access", {}) or {})
        return merged
    except Exception:
        return deepcopy(DEFAULT_SETTINGS)


def save_settings(settings: dict) -> dict:
    path = current_app.config.get("SETTINGS_FILE")
    if not path:
        raise RuntimeError("SETTINGS_FILE not configured")
    _ensure_parent_dir(path)
    with open(path, "w", encoding="utf-8") as f:
        json.dump(settings, f, indent=2, ensure_ascii=False)
    return settings


def update_settings(partial: dict) -> dict:
    settings = load_settings()
    if "company" in partial and isinstance(partial["company"], dict):
        settings["company"].update(partial["company"])
    if "email" in partial and isinstance(partial["email"], dict):
        settings["email"].update(partial["email"])
    if "access" in partial and isinstance(partial["access"], dict):
        settings["access"].update(partial["access"])
        roles = (settings.get("access") or {}).get("roles") or {}
        admin_role = roles.get("administrator")
        if isinstance(admin_role, dict):
            admin_role["*"] = True
            roles["administrator"] = admin_role
            settings["access"]["roles"] = roles
    return save_settings(settings)


def permissions_for_role(role: str) -> dict:
    settings = load_settings()
    access = (settings.get("access") or {}).get("roles") or {}
    role_map = access.get(role) or {}
    return role_map


def is_allowed(role: str, key: str) -> bool:
    perms = permissions_for_role(role)
    if perms.get("*") is True:
        return True
    return bool(perms.get(key))


def email_branding_context() -> dict:
    settings = load_settings()
    company = settings.get("company", {})
    return {
        "app_name": company.get("app_name") or "Jana ERP",
        "company_name": company.get("company_name") or company.get("app_name") or "Jana ERP",
        "logo_url": company.get("logo_url") or "",
        "support_email": company.get("support_email") or "",
        "primary_color": company.get("primary_color") or "#1f2937",
        "footer_text": company.get("footer_text") or DEFAULT_SETTINGS["company"]["footer_text"],
    }


def email_cc_admin_enabled() -> bool:
    settings = load_settings()
    email = settings.get("email", {})
    return bool(email.get("cc_admin", True))
