"""
platform_settings_service.py - Centralized Platform Settings & Brand Identity Management
Provides unified storage, retrieval, validation, public filtering, and CSS injection for Alliance Bank / Bnkfx.
"""

import os
import re
import time
import html

DEFAULT_PLATFORM_SETTINGS = {
    # 1. General Settings
    "platform_name": "Monveracu",
    "short_name": "Monveracu",
    "site_title": "Monveracu — Next-Generation Global Banking & Treasury",
    "site_description": "Smart personal banking, multi-currency accounts, instant global wire transfers, and premium cards.",
    "site_url": "http://localhost:8000",
    "support_email": "support@bnkfx.com",
    "support_phone": "+1 (800) 555-0199",
    "company_name": "Monveracu Financial Group Inc.",
    "company_address": "One Financial Plaza, Suite 400, New York, NY 10005, United States",
    "default_currency": "USD",
    "supported_currencies": ["USD", "EUR", "GBP", "CAD", "AUD", "USDC", "BTC", "ETH", "SOL"],
    "default_timezone": "UTC",
    "date_format": "Y-m-d",
    "time_format": "H:i:s",
    "maintenance_mode": False,
    "maintenance_mode_message": "Monveracu platform systems are temporarily undergoing scheduled maintenance. Services will resume shortly.",

    # 2. Brand Identity & Logos
    "primary_logo_url": "/assets/images/logo/logo-primary.svg",
    "dark_logo_url": "/assets/images/logo/logo-dark.svg",
    "light_logo_url": "/assets/images/logo/logo-light.svg",
    "compact_logo_url": "/assets/images/logo/logo-compact.svg",
    "icon_logo_url": "/assets/images/logo/logo-icon.svg",
    "favicon_url": "/assets/images/logo/favicon.ico",

    # Brand Colors
    "primary_color": "#0056B3",
    "primary_hover": "#004085",
    "secondary_color": "#12151B",
    "accent_color": "#20C997",
    "bg_color": "#0B0D10",
    "card_color": "#171A21",
    "text_primary": "#F8FAFC",
    "text_secondary": "#9CA6BA",
    "border_color": "#292E38",
    "success_color": "#20C997",
    "warning_color": "#F5B942",
    "error_color": "#F05D6C",

    # Typography & Appearance Presets
    "heading_font": "Inter, -apple-system, sans-serif",
    "body_font": "Inter, -apple-system, sans-serif",
    "border_radius_preset": "rounded-2xl",  # rounded-lg, rounded-xl, rounded-2xl, rounded-3xl
    "theme_preference": "dark",             # dark, light, system
    "allow_user_theme_switch": True,

    # 3. Contact & Support Details
    "customer_service_hours": "24/7/365 Global Operations Desk",
    "help_center_url": "/support",
    "support_portal_url": "/support",

    # 4. Social Links
    "social_links": {
        "facebook": {"url": "https://facebook.com/monveracu", "enabled": True},
        "x": {"url": "https://x.com/monveracu", "enabled": True},
        "linkedin": {"url": "https://linkedin.com/company/monveracu", "enabled": True},
        "instagram": {"url": "https://instagram.com/monveracu", "enabled": True},
        "youtube": {"url": "https://youtube.com/@monveracu", "enabled": False},
        "telegram": {"url": "https://t.me/monveracu_official", "enabled": True}
    },

    # 5. Authentication & Registration Settings
    "allow_registrations": True,
    "require_email_verification": True,
    "require_admin_approval": False,
    "allow_password_reset": True,
    "enable_2fa": True,
    "session_timeout_minutes": 120,
    "min_password_length": 8,

    # 6. Email Branding
    "email_sender_name": "Monveracu Banking Operations",
    "email_from_address": "notifications@bnkfx.com",
    "email_logo_url": "/assets/images/logo/logo-primary.svg",
    "email_accent_color": "#0056B3",
    "email_footer_text": "© 2026 Monveracu Inc. All rights reserved. Member FDIC / SIPC insured.",
    "email_signature": "The Monveracu Operations & Compliance Team",

    # 7. Localization
    "default_language": "en",
    "number_format": "standard",  # standard (1,234.56), european (1.234,56)

    # 8. SEO & Public Metadata
    "seo_keywords": "monveracu, digital banking, personal accounts, debit cards, global transfers, wealth custody",
    "og_title": "Monveracu — Next-Generation Global Banking & Treasury",
    "og_description": "Smart personal banking, multi-currency accounts, instant global wire transfers, and premium cards.",
    "og_image": "/assets/images/og-card.png",
    "robots_directive": "index, follow",

    # 9. Legal Content
    "legal": {
        "terms_of_service": "Welcome to Monveracu. By opening an account or utilizing our banking, custodial, or card services, you agree to our Terms of Service.",
        "privacy_policy": "Your data confidentiality is guaranteed. Monveracu does not sell personal or financial transaction records to advertisers.",
        "risk_disclosure": "Financial investments and digital currency transactions involve market fluctuations and liquidity considerations.",
        "copyright_text": "© 2026 Monveracu Inc. All rights reserved. Member FDIC / SIPC insured."
    }
}


def get_platform_settings(STATE=None):
    """
    Returns the active merged platform configuration from runtime state or defaults.
    """
    if STATE and "platform_settings" in STATE:
        merged = dict(DEFAULT_PLATFORM_SETTINGS)
        # Deep merge dicts
        for k, v in STATE["platform_settings"].items():
            if isinstance(v, dict) and isinstance(merged.get(k), dict):
                merged[k] = dict(merged[k])
                merged[k].update(v)
            else:
                merged[k] = v
        return merged
    return dict(DEFAULT_PLATFORM_SETTINGS)


def get_public_settings(STATE=None):
    """
    Returns only safe public-facing platform settings, strictly omitting private secrets.
    """
    cfg = get_platform_settings(STATE)
    return {
        "platform_name": cfg.get("platform_name"),
        "short_name": cfg.get("short_name"),
        "site_title": cfg.get("site_title"),
        "site_description": cfg.get("site_description"),
        "site_url": cfg.get("site_url"),
        "support_email": cfg.get("support_email"),
        "support_phone": cfg.get("support_phone"),
        "company_name": cfg.get("company_name"),
        "company_address": cfg.get("company_address"),
        "default_currency": cfg.get("default_currency"),
        "supported_currencies": cfg.get("supported_currencies"),
        "maintenance_mode": cfg.get("maintenance_mode", False),
        "maintenance_mode_message": cfg.get("maintenance_mode_message"),
        "logos": {
            "primary": cfg.get("primary_logo_url"),
            "dark": cfg.get("dark_logo_url"),
            "light": cfg.get("light_logo_url"),
            "compact": cfg.get("compact_logo_url"),
            "icon": cfg.get("icon_logo_url"),
            "favicon": cfg.get("favicon_url")
        },
        "brand_colors": {
            "primary": cfg.get("primary_color"),
            "primary_hover": cfg.get("primary_hover"),
            "secondary": cfg.get("secondary_color"),
            "accent": cfg.get("accent_color"),
            "background": cfg.get("bg_color"),
            "card": cfg.get("card_color"),
            "text": cfg.get("text_primary")
        },
        "appearance": {
            "border_radius": cfg.get("border_radius_preset"),
            "theme_preference": cfg.get("theme_preference")
        },
        "social_links": {k: v for k, v in cfg.get("social_links", {}).items() if v.get("enabled")},
        "legal": cfg.get("legal", {})
    }


def is_super_admin(user):
    """
    Validates whether the user is an authorized Super Administrator.
    """
    if not user or not isinstance(user, dict):
        return False
    if user.get("role") == "super_admin":
        return True
    if user.get("id") == 1:
        return True
    if str(user.get("email", "")).lower() == "admin@bnkfx.com":
        return True
    return False


def is_hex_color(val):
    return bool(re.match(r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$", str(val).strip()))


def update_platform_settings(data, STATE, actor_user=None):
    """
    Validates Super Admin authorization and submitted fields, updates runtime STATE,
    and logs the mutation to audit trail.
    Returns: (bool success, str message)
    """
    # 1. Enforce Super Admin Authorization
    if actor_user is not None and not is_super_admin(actor_user):
        return False, "Access denied. Only Super Administrators can modify global platform settings."

    current = get_platform_settings(STATE)
    changes = []

    # General Settings
    if "platform_name" in data and str(data["platform_name"]).strip():
        new_name = str(data["platform_name"]).strip()
        if new_name != current.get("platform_name"):
            changes.append(f"platform_name: {current.get('platform_name')} -> {new_name}")
            current["platform_name"] = new_name
            # Also keep email sender and site title aligned if appropriate
            current["short_name"] = str(data.get("short_name", new_name)).strip()

    if "site_title" in data and str(data["site_title"]).strip():
        current["site_title"] = str(data["site_title"]).strip()
    if "site_description" in data:
        current["site_description"] = str(data["site_description"]).strip()
    if "site_url" in data and str(data["site_url"]).strip():
        current["site_url"] = str(data["site_url"]).strip()
    if "support_email" in data and "@" in str(data["support_email"]):
        current["support_email"] = str(data["support_email"]).strip()
    if "support_phone" in data:
        current["support_phone"] = str(data["support_phone"]).strip()
    if "company_name" in data and str(data["company_name"]).strip():
        current["company_name"] = str(data["company_name"]).strip()
    if "company_address" in data:
        current["company_address"] = str(data["company_address"]).strip()
    if "default_currency" in data and str(data["default_currency"]).strip():
        current["default_currency"] = str(data["default_currency"]).strip().upper()
    if "default_timezone" in data:
        current["default_timezone"] = str(data["default_timezone"]).strip()
    if "maintenance_mode" in data:
        m_val = str(data["maintenance_mode"]).lower() in ["1", "true", "on", "yes"]
        if m_val != current.get("maintenance_mode"):
            changes.append(f"maintenance_mode: {current.get('maintenance_mode')} -> {m_val}")
        current["maintenance_mode"] = m_val
    if "maintenance_mode_message" in data:
        current["maintenance_mode_message"] = str(data["maintenance_mode_message"]).strip()

    # Brand Colors
    color_keys = ["primary_color", "primary_hover", "secondary_color", "accent_color",
                  "bg_color", "card_color", "text_primary", "text_secondary", "border_color",
                  "success_color", "warning_color", "error_color"]
    for ck in color_keys:
        if ck in data and is_hex_color(data[ck]):
            c_val = str(data[ck]).strip()
            if c_val != current.get(ck):
                changes.append(f"{ck}: {current.get(ck)} -> {c_val}")
                current[ck] = c_val

    # Logos & Icons
    logo_keys = ["primary_logo_url", "dark_logo_url", "light_logo_url", "compact_logo_url", "icon_logo_url", "favicon_url"]
    for lk in logo_keys:
        if lk in data and str(data[lk]).strip():
            current[lk] = str(data[lk]).strip()

    # Typography & Appearance
    if "heading_font" in data:
        current["heading_font"] = str(data["heading_font"]).strip()
    if "border_radius_preset" in data:
        current["border_radius_preset"] = str(data["border_radius_preset"]).strip()
    if "theme_preference" in data:
        current["theme_preference"] = str(data["theme_preference"]).strip()
    if "allow_user_theme_switch" in data:
        current["allow_user_theme_switch"] = str(data["allow_user_theme_switch"]).lower() in ["1", "true", "on", "yes"]

    # Authentication & Registration Settings
    auth_flags = ["allow_registrations", "require_email_verification", "require_admin_approval", "allow_password_reset", "enable_2fa"]
    for af in auth_flags:
        if af in data:
            current[af] = str(data[af]).lower() in ["1", "true", "on", "yes"]
    if "session_timeout_minutes" in data:
        try:
            current["session_timeout_minutes"] = max(5, int(data["session_timeout_minutes"]))
        except (ValueError, TypeError):
            pass
    if "min_password_length" in data:
        try:
            current["min_password_length"] = max(6, int(data["min_password_length"]))
        except (ValueError, TypeError):
            pass

    # Social Links
    if "social_links" in data and isinstance(data["social_links"], dict):
        for s_platform, s_info in data["social_links"].items():
            if s_platform in current.get("social_links", {}):
                current["social_links"][s_platform]["url"] = s_info.get("url", current["social_links"][s_platform]["url"])
                current["social_links"][s_platform]["enabled"] = bool(s_info.get("enabled", True))

    # Email Branding
    if "email_sender_name" in data and str(data["email_sender_name"]).strip():
        current["email_sender_name"] = str(data["email_sender_name"]).strip()
    if "email_from_address" in data and "@" in str(data["email_from_address"]):
        current["email_from_address"] = str(data["email_from_address"]).strip()
    if "email_logo_url" in data:
        current["email_logo_url"] = str(data["email_logo_url"]).strip()
    if "email_accent_color" in data and is_hex_color(data["email_accent_color"]):
        current["email_accent_color"] = str(data["email_accent_color"]).strip()
    if "email_footer_text" in data:
        current["email_footer_text"] = str(data["email_footer_text"]).strip()

    # SEO & Metadata
    if "seo_keywords" in data:
        current["seo_keywords"] = str(data["seo_keywords"]).strip()
    if "og_title" in data:
        current["og_title"] = str(data["og_title"]).strip()
    if "og_description" in data:
        current["og_description"] = str(data["og_description"]).strip()
    if "og_image" in data:
        current["og_image"] = str(data["og_image"]).strip()

    # Legal Content
    if "legal" in data and isinstance(data["legal"], dict):
        current.setdefault("legal", {})
        for lk in ["terms_of_service", "privacy_policy", "risk_disclosure", "copyright_text"]:
            if lk in data["legal"]:
                current["legal"][lk] = str(data["legal"][lk]).strip()
    elif any(k in data for k in ["terms_of_service", "privacy_policy", "risk_disclosure", "copyright_text"]):
        current.setdefault("legal", {})
        for lk in ["terms_of_service", "privacy_policy", "risk_disclosure", "copyright_text"]:
            if lk in data:
                current["legal"][lk] = str(data[lk]).strip()

    # Persist in STATE
    STATE["platform_settings"] = current

    # Log to Security Audit Trail
    audit_desc = f"Platform configuration updated by Super Admin ({len(changes)} values changed: {', '.join(changes[:4]) if changes else 'saved'})"
    STATE.setdefault("audit_logs", []).append({
        "action": "admin_platform_settings_updated",
        "user_id": actor_user.get("id", 1) if actor_user else 1,
        "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
        "details": audit_desc
    })

    return True, "Platform settings and brand identity updated successfully."


def is_maintenance_mode(STATE=None, user=None, path=""):
    """
    Checks if maintenance mode is active.
    Super Admins and administrators, as well as admin routes, static assets, and auth routes are exempt.
    """
    cfg = get_platform_settings(STATE)
    if not cfg.get("maintenance_mode", False):
        return False

    # Allow Super Admins & Admins
    if user and is_super_admin(user):
        return False
    if user and user.get("role") in ["admin", "super_admin"]:
        return False

    # Exclude admin routes, auth login, assets, public settings
    safe_prefixes = [
        "/admin",
        "/login",
        "/logout",
        "/assets/",
        "/api/settings/public",
        "/settings/public"
    ]
    for p in safe_prefixes:
        if path == p or path.startswith(p):
            return False

    return True


def render_maintenance_page(settings):
    """
    Renders an institutional branded maintenance response page.
    """
    name = settings.get("platform_name", "Alliance Bank")
    msg = settings.get("maintenance_mode_message", "Platform systems are temporarily undergoing scheduled maintenance. Services will resume shortly.")
    bg = settings.get("bg_color", "#0B0D10")
    support_email = settings.get("support_email", "support@bnkfx.com")

    return f"""<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scheduled Maintenance | {name}</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="h-full bg-[{bg}] text-slate-100 flex items-center justify-center p-4 antialiased">
    <div class="max-w-md w-full text-center space-y-6 p-8 rounded-2xl bg-[#171A21] border border-[#292E38] shadow-2xl">
        <div class="w-16 h-16 mx-auto rounded-2xl bg-amber-500/10 border border-amber-500/30 flex items-center justify-center text-amber-400 text-2xl shadow-lg shadow-amber-500/10">
            <i class="fa-solid fa-wrench"></i>
        </div>
        <div class="space-y-2">
            <h1 class="text-2xl font-bold tracking-tight text-white">{name}</h1>
            <p class="text-xs uppercase tracking-widest text-amber-400 font-semibold">Scheduled Maintenance in Progress</p>
        </div>
        <div class="p-4 rounded-xl bg-[#0B0D10] border border-[#292E38] text-sm text-slate-300 leading-relaxed text-left">
            <i class="fa-solid fa-circle-info text-amber-400 mr-2"></i>
            {html.escape(msg)}
        </div>
        <div class="pt-2 text-xs text-slate-400 space-y-1">
            <p>Our engineering team is performing scheduled infrastructure upgrades.</p>
            <p>For urgent inquiries, reach out to <a href="mailto:{support_email}" class="text-blue-400 underline">{support_email}</a>.</p>
        </div>
        <div class="pt-4 border-t border-[#292E38] flex items-center justify-between text-xs text-slate-500">
            <span>&copy; {time.strftime('%Y')} {name}</span>
            <a href="/login" class="text-slate-400 hover:text-slate-200">Staff Portal &rarr;</a>
        </div>
    </div>
</body>
</html>"""


def generate_brand_css(settings):
    """
    Generates CSS custom properties injected dynamically into <head>.
    Ensures that updating primary_color instantly updates buttons, focus rings, borders, and highlights.
    """
    pri = settings.get("primary_color", "#246BFD")
    pri_hover = settings.get("primary_hover", "#1858D8")
    sec = settings.get("secondary_color", "#12151B")
    acc = settings.get("accent_color", "#20C997")
    bg = settings.get("bg_color", "#0B0D10")
    card = settings.get("card_color", "#171A21")
    txt = settings.get("text_primary", "#F8FAFC")
    border = settings.get("border_color", "#292E38")

    return f"""
    <style id="platform-branding-styles">
        :root {{
            --brand-primary: {pri};
            --brand-primary-hover: {pri_hover};
            --brand-secondary: {sec};
            --brand-accent: {acc};
            --brand-bg: {bg};
            --brand-card: {card};
            --brand-text: {txt};
            --brand-border: {border};
        }}
        .bg-primary {{ background-color: var(--brand-primary) !important; }}
        .text-primary {{ color: var(--brand-primary) !important; }}
        .border-primary {{ border-color: var(--brand-primary) !important; }}
        .hover\\:bg-primary-hover:hover {{ background-color: var(--brand-primary-hover) !important; }}
        .brand-gradient {{
            background: linear-gradient(135deg, var(--brand-primary) 0%, var(--brand-primary-hover) 100%) !important;
        }}
        .brand-btn {{
            background-color: var(--brand-primary) !important;
            color: #FFFFFF !important;
            transition: all 0.2s ease;
        }}
        .brand-btn:hover {{
            background-color: var(--brand-primary-hover) !important;
        }}
    </style>
    """
