import base64
import hashlib
import os
import secrets
from pathlib import Path

from cryptography.fernet import Fernet, InvalidToken
from django.conf import settings
from django.db import transaction
from django.utils import timezone

from apps.audit.services import record_audit_event
from apps.system_admin.models import (
    ApiIntegrationKey,
    ConfigurationHistory,
    SystemConfigurationEntry,
)


def _derive_fernet() -> Fernet:
    raw = settings.SECRET_KEY.encode("utf-8")
    digest = hashlib.sha256(b"maya_os_sysadmin_v1:" + raw).digest()
    return Fernet(base64.urlsafe_b64encode(digest))


def encrypt_secret(plaintext: str) -> str:
    if not plaintext:
        return ""
    return _derive_fernet().encrypt(plaintext.encode("utf-8")).decode("utf-8")


def decrypt_secret(token: str) -> str:
    if not token:
        return ""
    try:
        return _derive_fernet().decrypt(token.encode("utf-8")).decode("utf-8")
    except InvalidToken:
        return ""


def mask_secret(plaintext_or_empty: str) -> str:
    if not plaintext_or_empty:
        return ""
    tail = plaintext_or_empty[-4:] if len(plaintext_or_empty) > 4 else ""
    return f"••••••••{tail}"


DEFAULT_CONFIG_SCHEMA: list[dict] = [
    # GENERAL
    {"category": "GENERAL", "key": "platform_name", "label": "Platform Name", "default": {"value": "Maya OS Enterprise ERP"}, "sensitive": False},
    {"category": "GENERAL", "key": "default_timezone", "label": "Default Timezone", "default": {"value": "Asia/Kathmandu"}, "sensitive": False},
    {"category": "GENERAL", "key": "default_calendar", "label": "Default Calendar Preference", "default": {"value": "BS"}, "sensitive": False},
    # SECURITY
    {"category": "SECURITY", "key": "password_min_length", "label": "Minimum Password Length", "default": {"value": 10}, "sensitive": False},
    {"category": "SECURITY", "key": "require_mfa_for_admins", "label": "Require MFA for Admins & Super Admins", "default": {"value": True}, "sensitive": False},
    {"category": "SECURITY", "key": "session_idle_timeout_minutes", "label": "Session Idle Timeout (Minutes)", "default": {"value": 60}, "sensitive": False},
    {"category": "SECURITY", "key": "max_failed_logins", "label": "Brute-Force Lockout Threshold", "default": {"value": 5}, "sensitive": False},
    {"category": "SECURITY", "key": "lockout_minutes", "label": "Account Lockout Duration (Minutes)", "default": {"value": 15}, "sensitive": False},
    {"category": "SECURITY", "key": "dual_control_critical_ops", "label": "Dual Approver Required for Critical Ops", "default": {"value": True}, "sensitive": False},
    {"category": "SECURITY", "key": "admin_ip_allowlist", "label": "Admin IP Allowlist (empty = all)", "default": {"ips": []}, "sensitive": False},
    # ACCOUNTING
    {"category": "ACCOUNTING", "key": "base_currency", "label": "Default Base Currency", "default": {"value": "NPR"}, "sensitive": False},
    {"category": "ACCOUNTING", "key": "strict_period_lock", "label": "Block Posting to Locked/Closed Periods", "default": {"value": True}, "sensitive": False},
    {"category": "ACCOUNTING", "key": "allow_negative_cash", "label": "Allow Negative Cash Warning Only", "default": {"value": False}, "sensitive": False},
    # TAX
    {"category": "TAX", "key": "default_vat_rate", "label": "Nepal Standard VAT Rate (%)", "default": {"value": "13.00"}, "sensitive": False},
    {"category": "TAX", "key": "default_tds_contractor_rate", "label": "Construction Contractor TDS (%)", "default": {"value": "1.50"}, "sensitive": False},
    # WORKFLOW
    {"category": "WORKFLOW", "key": "high_value_voucher_threshold", "label": "High-Value Dual Approval Threshold (NPR)", "default": {"value": "500000.00"}, "sensitive": False},
    {"category": "WORKFLOW", "key": "maker_checker_enforced", "label": "Enforce Maker-Checker Separation", "default": {"value": True}, "sensitive": False},
    # NOTIFICATION
    {"category": "NOTIFICATION", "key": "smtp_host", "label": "SMTP Host", "default": {"value": ""}, "sensitive": False},
    {"category": "NOTIFICATION", "key": "smtp_port", "label": "SMTP Port", "default": {"value": 587}, "sensitive": False},
    {"category": "NOTIFICATION", "key": "smtp_username", "label": "SMTP Username", "default": {"value": ""}, "sensitive": False},
    {"category": "NOTIFICATION", "key": "smtp_password", "label": "SMTP Password / App Secret", "default": {"has_secret": False}, "sensitive": True},
    {"category": "NOTIFICATION", "key": "sms_provider", "label": "SMS Gateway Provider", "default": {"value": "SPARROW_SMS"}, "sensitive": False},
    {"category": "NOTIFICATION", "key": "sms_api_secret", "label": "SMS API Token", "default": {"has_secret": False}, "sensitive": True},
    # STORAGE
    {"category": "STORAGE", "key": "max_upload_mb", "label": "Maximum Attachment Upload Size (MB)", "default": {"value": 25}, "sensitive": False},
    {"category": "STORAGE", "key": "backup_root_path", "label": "Backup Storage Directory", "default": {"value": str(Path(settings.PRIVATE_DOCUMENT_ROOT) / "backups")}, "sensitive": False},
    {"category": "STORAGE", "key": "allowed_mime_extensions", "label": "Allowed File Extensions", "default": {"extensions": ["pdf", "xlsx", "csv", "png", "jpg", "jpeg", "sql", "gz", "tar"]}, "sensitive": False},
    # INTEGRATION
    {"category": "INTEGRATION", "key": "nrb_fx_sync_enabled", "label": "Enable NRB FX Auto-Sync", "default": {"value": True}, "sensitive": False},
    # DOCUMENT
    {"category": "DOCUMENT", "key": "default_paper_size", "label": "Default Print Paper Size", "default": {"value": "A4"}, "sensitive": False},
    {"category": "DOCUMENT", "key": "pdf_footer_text", "label": "System Report Footer Text", "default": {"value": "Maya OS Enterprise ERP — Server Verified Output"}, "sensitive": False},
]


class SystemConfigurationService:
    @staticmethod
    def get_effective_configs(*, company=None, category: str | None = None) -> list[dict]:
        global_entries = {
            (e.category, e.key): e
            for e in SystemConfigurationEntry.objects.filter(scope=SystemConfigurationEntry.Scope.GLOBAL)
        }
        company_entries = {}
        if company is not None:
            company_entries = {
                (e.category, e.key): e
                for e in SystemConfigurationEntry.objects.filter(
                    scope=SystemConfigurationEntry.Scope.COMPANY, company=company
                )
            }

        results = []
        seen = set()
        for spec in DEFAULT_CONFIG_SCHEMA:
            cat, key = spec["category"], spec["key"]
            if category and cat != category:
                continue
            seen.add((cat, key))
            c_entry = company_entries.get((cat, key))
            g_entry = global_entries.get((cat, key))
            active = c_entry or g_entry
            if active:
                val = (
                    {"has_secret": bool(active.value_secret_encrypted), "masked_value": "••••••••" if active.value_secret_encrypted else ""}
                    if (active.is_sensitive or spec["sensitive"])
                    else active.value_json
                )
                source_scope = active.scope
                updated_at = active.updated_at.isoformat()
            else:
                val = spec["default"]
                source_scope = "DEFAULT"
                updated_at = None
            results.append(
                {
                    "category": cat,
                    "key": key,
                    "label": spec["label"],
                    "is_sensitive": spec["sensitive"],
                    "source_scope": source_scope,
                    "has_company_override": bool(c_entry),
                    "value": val,
                    "updated_at": updated_at,
                }
            )

        # Include custom dynamic keys created outside schema
        for (cat, key), entry in {**global_entries, **company_entries}.items():
            if (cat, key) in seen or (category and cat != category):
                continue
            val = (
                {"has_secret": bool(entry.value_secret_encrypted), "masked_value": "••••••••" if entry.value_secret_encrypted else ""}
                if entry.is_sensitive
                else entry.value_json
            )
            results.append(
                {
                    "category": cat,
                    "key": key,
                    "label": entry.label or key,
                    "is_sensitive": entry.is_sensitive,
                    "source_scope": entry.scope,
                    "has_company_override": (cat, key) in company_entries,
                    "value": val,
                    "updated_at": entry.updated_at.isoformat(),
                }
            )
        return results

    @staticmethod
    @transaction.atomic
    def upsert_config(
        *,
        scope: str,
        company,
        category: str,
        key: str,
        value,
        is_sensitive: bool = False,
        label: str = "",
        description: str = "",
        actor=None,
        reason: str = "",
    ) -> dict:
        if scope == SystemConfigurationEntry.Scope.GLOBAL:
            company = None
        schema_match = next((s for s in DEFAULT_CONFIG_SCHEMA if s["category"] == category and s["key"] == key), None)
        if schema_match and schema_match["sensitive"]:
            is_sensitive = True

        entry, created = SystemConfigurationEntry.objects.get_or_create(
            scope=scope,
            company=company,
            category=category,
            key=key,
            defaults={
                "label": label or (schema_match["label"] if schema_match else key),
                "is_sensitive": is_sensitive,
                "description": description,
                "updated_by": actor,
            },
        )
        prev_masked = (
            {"masked": mask_secret(decrypt_secret(entry.value_secret_encrypted))}
            if entry.is_sensitive
            else entry.value_json
        )
        if is_sensitive:
            secret_str = str(value.get("secret", "") if isinstance(value, dict) else value or "")
            if not secret_str and not created:
                raise ValueError("Secret value cannot be empty when updating sensitive setting.")
            entry.value_secret_encrypted = encrypt_secret(secret_str)
            entry.value_json = {"has_secret": True}
            entry.is_sensitive = True
            new_masked = {"masked": mask_secret(secret_str)}
        else:
            entry.value_json = value if isinstance(value, dict) else {"value": value}
            entry.is_sensitive = False
            new_masked = entry.value_json
        if label:
            entry.label = label
        if description:
            entry.description = description
        entry.updated_by = actor
        entry.save()

        ConfigurationHistory.objects.create(
            config_entry=entry,
            company=company,
            category=category,
            key=key,
            previous_value_masked=None if created else prev_masked,
            new_value_masked=new_masked,
            reason=reason or "Admin configuration update",
            changed_by=actor,
        )
        record_audit_event(
            company=company,
            actor=actor,
            action="CONFIG_UPDATED",
            entity_type="SystemConfigurationEntry",
            entity_id=str(entry.id),
            previous_state=None if created else prev_masked,
            new_state={"scope": scope, "category": category, "key": key, "value": new_masked},
        )
        return {
            "id": str(entry.id),
            "scope": entry.scope,
            "category": entry.category,
            "key": entry.key,
            "is_sensitive": entry.is_sensitive,
            "value": {"has_secret": True, "masked_value": "••••••••"} if entry.is_sensitive else entry.value_json,
            "updated_at": entry.updated_at.isoformat(),
        }

    @staticmethod
    def test_storage_target(company=None) -> dict:
        configs = {
            c["key"]: c["value"]
            for c in SystemConfigurationService.get_effective_configs(company=company, category="STORAGE")
        }
        backup_dir = Path((configs.get("backup_root_path") or {}).get("value") or (Path(settings.PRIVATE_DOCUMENT_ROOT) / "backups"))
        backup_dir.mkdir(parents=True, exist_ok=True)
        probe = backup_dir / ".maya_write_probe"
        probe.write_text("ok", encoding="utf-8")
        probe.unlink(missing_ok=True)
        return {"ok": True, "path": str(backup_dir), "writable": True}

    @staticmethod
    def test_smtp_config(company=None) -> dict:
        configs = {
            c["key"]: c for c in SystemConfigurationService.get_effective_configs(company=company, category="NOTIFICATION")
        }
        host = ((configs.get("smtp_host") or {}).get("value") or {}).get("value", "")
        port = ((configs.get("smtp_port") or {}).get("value") or {}).get("value", 587)
        has_secret = ((configs.get("smtp_password") or {}).get("value") or {}).get("has_secret", False)
        return {
            "ok": bool(host),
            "host": host,
            "port": port,
            "credentials_configured": bool(has_secret),
            "message": f"SMTP relay profile verified for {host}:{port}" if host else "SMTP host is not configured yet.",
        }


class ApiIntegrationService:
    @staticmethod
    @transaction.atomic
    def create_key(*, company, name: str, service_type: str, endpoint_url: str = "", scopes=None, actor=None) -> dict:
        raw_secret = f"maya_{secrets.token_urlsafe(24)}"
        prefix = raw_secret[:12]
        secret_hash = hashlib.sha256(raw_secret.encode("utf-8")).hexdigest()
        obj = ApiIntegrationKey.objects.create(
            company=company,
            name=name,
            service_type=service_type,
            endpoint_url=endpoint_url,
            key_prefix=prefix,
            secret_hash=secret_hash,
            secret_encrypted=encrypt_secret(raw_secret),
            scopes=scopes or [],
            created_by=actor,
        )
        record_audit_event(
            company=company,
            actor=actor,
            action="INTEGRATION_KEY_CREATED",
            entity_type="ApiIntegrationKey",
            entity_id=str(obj.id),
            new_state={"name": name, "service_type": service_type, "key_prefix": prefix},
        )
        return {
            "id": str(obj.id),
            "name": obj.name,
            "service_type": obj.service_type,
            "key_prefix": obj.key_prefix,
            "plaintext_secret_once": raw_secret,
            "created_at": obj.created_at.isoformat(),
        }

