import uuid
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.utils import timezone


class BackupArtifact(models.Model):
    class Scope(models.TextChoices):
        DATABASE = "DATABASE", "Database Dump"
        MEDIA = "MEDIA", "Files & Documents"
        FULL = "FULL", "Full System (DB + Media + Config)"
        CONFIG = "CONFIG", "Configuration Snapshot"

    class TriggerType(models.TextChoices):
        MANUAL = "MANUAL", "Manual"
        SCHEDULED = "SCHEDULED", "Scheduled"
        PRE_RESTORE = "PRE_RESTORE", "Pre-Restore Safety Snapshot"
        PRE_UPGRADE = "PRE_UPGRADE", "Pre-Upgrade Safety Snapshot"

    class Status(models.TextChoices):
        QUEUED = "QUEUED", "Queued"
        RUNNING = "RUNNING", "Running"
        COMPLETED = "COMPLETED", "Completed"
        VERIFIED = "VERIFIED", "Verified"
        FAILED = "FAILED", "Failed"
        EXPIRED = "EXPIRED", "Expired"
        DELETED = "DELETED", "Deleted"

    class VerificationStatus(models.TextChoices):
        UNVERIFIED = "UNVERIFIED", "Unverified"
        PASS = "PASS", "Checksum & Structure Pass"
        FAIL = "FAIL", "Verification Failed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    backup_code = models.CharField(max_length=40, unique=True, db_index=True)
    scope = models.CharField(max_length=16, choices=Scope.choices, default=Scope.DATABASE)
    trigger_type = models.CharField(max_length=16, choices=TriggerType.choices, default=TriggerType.MANUAL)
    company = models.ForeignKey(
        "tenancy.Company",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="backup_artifacts",
    )
    db_engine = models.CharField(max_length=32, default="sqlite")
    file_path = models.CharField(max_length=500, blank=True)
    storage_target = models.CharField(max_length=32, default="LOCAL")
    size_bytes = models.BigIntegerField(default=0)
    sha256_checksum = models.CharField(max_length=64, blank=True)
    is_encrypted = models.BooleanField(default=False)
    encryption_key_id = models.CharField(max_length=64, blank=True)
    app_version = models.CharField(max_length=32, default="2.4.0")
    schema_migration_head = models.CharField(max_length=120, blank=True)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.QUEUED, db_index=True)
    verification_status = models.CharField(
        max_length=16, choices=VerificationStatus.choices, default=VerificationStatus.UNVERIFIED
    )
    verified_at = models.DateTimeField(null=True, blank=True)
    verification_report = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    retention_expires_at = models.DateTimeField(null=True, blank=True)
    notes = models.TextField(blank=True)
    error_message = models.TextField(blank=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="created_backups"
    )
    created_at = models.DateTimeField(default=timezone.now, db_index=True)
    completed_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self) -> str:
        return f"{self.backup_code} [{self.scope} / {self.status}]"


class BackupSchedule(models.Model):
    class Frequency(models.TextChoices):
        DAILY = "DAILY", "Daily"
        WEEKLY = "WEEKLY", "Weekly"
        MONTHLY = "MONTHLY", "Monthly"
        CUSTOM_CRON = "CUSTOM_CRON", "Custom Cron"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=120, unique=True)
    frequency = models.CharField(max_length=16, choices=Frequency.choices, default=Frequency.DAILY)
    cron_expression = models.CharField(max_length=64, default="0 2 * * *")
    scope = models.CharField(max_length=16, choices=BackupArtifact.Scope.choices, default=BackupArtifact.Scope.FULL)
    storage_target = models.CharField(max_length=32, default="LOCAL")
    encrypt_backup = models.BooleanField(default=True)
    retention_count = models.PositiveIntegerField(default=14)
    retention_days = models.PositiveIntegerField(default=30)
    verify_after_backup = models.BooleanField(default=True)
    is_active = models.BooleanField(default=True)
    last_run_at = models.DateTimeField(null=True, blank=True)
    next_run_at = models.DateTimeField(null=True, blank=True)
    last_status = models.CharField(max_length=32, blank=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["name"]

    def __str__(self) -> str:
        return f"{self.name} ({self.cron_expression})"


class RestoreJob(models.Model):
    class RestoreMode(models.TextChoices):
        FULL_SYSTEM = "FULL_SYSTEM", "Full System Restore"
        DATABASE_ONLY = "DATABASE_ONLY", "Database Only"
        FILES_ONLY = "FILES_ONLY", "Files Only"
        ISOLATED_TEST = "ISOLATED_TEST", "Isolated Sandbox Recovery Test"

    class Status(models.TextChoices):
        PENDING_APPROVAL = "PENDING_APPROVAL", "Pending Dual Approval"
        APPROVED = "APPROVED", "Approved"
        DRY_RUN_PASS = "DRY_RUN_PASS", "Dry Run Passed"
        RUNNING = "RUNNING", "Restoring"
        COMPLETED = "COMPLETED", "Completed"
        FAILED = "FAILED", "Failed"
        ROLLED_BACK = "ROLLED_BACK", "Rolled Back"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    restore_code = models.CharField(max_length=40, unique=True, db_index=True)
    source_backup = models.ForeignKey(BackupArtifact, on_delete=models.PROTECT, related_name="restore_jobs")
    restore_mode = models.CharField(max_length=20, choices=RestoreMode.choices, default=RestoreMode.ISOLATED_TEST)
    target_company = models.ForeignKey(
        "tenancy.Company", on_delete=models.SET_NULL, null=True, blank=True
    )
    pre_restore_snapshot = models.ForeignKey(
        BackupArtifact, on_delete=models.SET_NULL, null=True, blank=True, related_name="rollback_for_restores"
    )
    requires_dual_approval = models.BooleanField(default=True)
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="approved_restores"
    )
    maintenance_mode_enabled = models.BooleanField(default=False)
    status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING_APPROVAL)
    integrity_check_result = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    log_output = models.TextField(blank=True)
    initiated_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="initiated_restores"
    )
    started_at = models.DateTimeField(default=timezone.now)
    completed_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["-started_at"]


class DisasterRecoveryPlan(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    plan_name = models.CharField(max_length=160, default="Maya OS Enterprise Primary DR Plan")
    rpo_minutes = models.PositiveIntegerField(default=1440)
    rto_minutes = models.PositiveIntegerField(default=120)
    primary_contact_user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True
    )
    secondary_contact_email = models.EmailField(blank=True)
    offsite_storage_uri = models.CharField(max_length=300, blank=True)
    escalation_notes = models.TextField(blank=True)
    drill_frequency_days = models.PositiveIntegerField(default=30)
    last_drill_at = models.DateTimeField(null=True, blank=True)
    last_drill_status = models.CharField(max_length=32, default="NOT_RUN")
    checklist_steps = models.JSONField(default=list, blank=True)
    updated_at = models.DateTimeField(auto_now=True)


class InstallationSession(models.Model):
    class Status(models.TextChoices):
        NOT_STARTED = "NOT_STARTED", "Not Started"
        IN_PROGRESS = "IN_PROGRESS", "In Progress"
        COMPLETED = "COMPLETED", "Completed"
        LOCKED = "LOCKED", "Locked"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    current_step = models.PositiveSmallIntegerField(default=1)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.IN_PROGRESS)
    preflight_results = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    db_probe_results = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    step_payloads = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    installed_version = models.CharField(max_length=32, default="2.4.0")
    completed_at = models.DateTimeField(null=True, blank=True)
    completed_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


class SoftwareRelease(models.Model):
    class Channel(models.TextChoices):
        STABLE = "STABLE", "Stable"
        LTS = "LTS", "Long-Term Support"
        BETA = "BETA", "Beta / Staging"

    class SignatureStatus(models.TextChoices):
        VERIFIED = "VERIFIED", "Verified"
        UNSIGNED = "UNSIGNED", "Unsigned"
        INVALID = "INVALID", "Invalid Signature / Checksum"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    version = models.CharField(max_length=32, unique=True)
    build_number = models.CharField(max_length=64, blank=True)
    channel = models.CharField(max_length=12, choices=Channel.choices, default=Channel.STABLE)
    release_notes = models.TextField(blank=True)
    changelog_items = models.JSONField(default=list, blank=True)
    package_path = models.CharField(max_length=400, blank=True)
    git_ref = models.CharField(max_length=64, blank=True)
    manifest_sha256 = models.CharField(max_length=64, blank=True)
    signature_status = models.CharField(
        max_length=16, choices=SignatureStatus.choices, default=SignatureStatus.UNSIGNED
    )
    min_compatible_version = models.CharField(max_length=32, default="1.0.0")
    requires_migration = models.BooleanField(default=True)
    migrations_expected = models.JSONField(default=list, blank=True)
    is_current = models.BooleanField(default=False)
    released_at = models.DateTimeField(default=timezone.now)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-released_at", "-version"]

    def __str__(self) -> str:
        return f"v{self.version} ({self.channel})"


class SoftwareDeploymentJob(models.Model):
    class ActionType(models.TextChoices):
        INSTALL = "INSTALL", "Install"
        UPGRADE = "UPGRADE", "Upgrade"
        ROLLBACK = "ROLLBACK", "Rollback"
        MIGRATE_ONLY = "MIGRATE_ONLY", "Schema Migration Only"

    class Status(models.TextChoices):
        PENDING = "PENDING", "Pending"
        PREFLIGHT_PASS = "PREFLIGHT_PASS", "Preflight Passed"
        BACKING_UP = "BACKING_UP", "Pre-Upgrade Backup"
        UPDATING = "UPDATING", "Applying Release"
        MIGRATING = "MIGRATING", "Running Migrations"
        VERIFYING = "VERIFYING", "Verifying Health"
        COMPLETED = "COMPLETED", "Completed"
        FAILED = "FAILED", "Failed"
        ROLLED_BACK = "ROLLED_BACK", "Rolled Back"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    deployment_code = models.CharField(max_length=40, unique=True, db_index=True)
    action_type = models.CharField(max_length=16, choices=ActionType.choices, default=ActionType.UPGRADE)
    from_version = models.CharField(max_length=32, blank=True)
    to_version = models.ForeignKey(SoftwareRelease, on_delete=models.PROTECT, related_name="deployment_jobs")
    pre_upgrade_backup = models.ForeignKey(
        BackupArtifact, on_delete=models.SET_NULL, null=True, blank=True, related_name="deployment_snapshots"
    )
    preflight_checks = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)
    execution_log = models.TextField(blank=True)
    rollback_target_version = models.CharField(max_length=32, blank=True)
    initiated_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True
    )
    started_at = models.DateTimeField(default=timezone.now)
    completed_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["-started_at"]


class SystemMaintenanceState(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    is_maintenance_mode = models.BooleanField(default=False)
    reason = models.CharField(max_length=255, blank=True)
    banner_message = models.TextField(blank=True)
    allowed_ips = models.JSONField(default=list, blank=True)
    block_non_admin_writes = models.BooleanField(default=True)
    enabled_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True
    )
    enabled_at = models.DateTimeField(null=True, blank=True)
    scheduled_end_at = models.DateTimeField(null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True)


class SystemConfigurationEntry(models.Model):
    class Scope(models.TextChoices):
        GLOBAL = "GLOBAL", "Global Platform"
        COMPANY = "COMPANY", "Company Override"

    class Category(models.TextChoices):
        GENERAL = "GENERAL", "Global System Settings"
        SECURITY = "SECURITY", "Security & Session Policy"
        ACCOUNTING = "ACCOUNTING", "Accounting & Financial Defaults"
        TAX = "TAX", "Tax & Compliance Defaults"
        WORKFLOW = "WORKFLOW", "Approval & Workflow Rules"
        NOTIFICATION = "NOTIFICATION", "Email / SMS / Notification Settings"
        STORAGE = "STORAGE", "Storage & File Limits"
        INTEGRATION = "INTEGRATION", "API & Integration Defaults"
        DOCUMENT = "DOCUMENT", "Document & Print Defaults"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    scope = models.CharField(max_length=12, choices=Scope.choices, default=Scope.GLOBAL)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, null=True, blank=True, related_name="config_entries"
    )
    category = models.CharField(max_length=20, choices=Category.choices, db_index=True)
    key = models.CharField(max_length=80, db_index=True)
    label = models.CharField(max_length=160, blank=True)
    value_json = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    value_secret_encrypted = models.TextField(blank=True)
    is_sensitive = models.BooleanField(default=False)
    description = models.TextField(blank=True)
    updated_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True
    )
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = [("scope", "company", "category", "key")]
        ordering = ["category", "key"]

    def __str__(self) -> str:
        c = self.company.code if self.company else "GLOBAL"
        return f"{c}:{self.category}.{self.key}"


class ConfigurationHistory(models.Model):
    """Append-only configuration change trail with sensitive values masked."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    config_entry = models.ForeignKey(
        SystemConfigurationEntry, on_delete=models.CASCADE, related_name="history"
    )
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.SET_NULL, null=True, blank=True
    )
    category = models.CharField(max_length=20)
    key = models.CharField(max_length=80)
    previous_value_masked = models.JSONField(null=True, blank=True, encoder=DjangoJSONEncoder)
    new_value_masked = models.JSONField(null=True, blank=True, encoder=DjangoJSONEncoder)
    reason = models.CharField(max_length=255, blank=True)
    changed_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True
    )
    changed_at = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ["-changed_at"]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            raise PermissionError("ConfigurationHistory is append-only.")
        super().save(*args, **kwargs)


class ApiIntegrationKey(models.Model):
    class ServiceType(models.TextChoices):
        WEBHOOK = "WEBHOOK", "Outbound Webhook"
        SMTP = "SMTP", "SMTP Relay"
        SMS = "SMS", "SMS Gateway"
        NRB_FX = "NRB_FX", "NRB FX Feed"
        S3 = "S3", "S3 Object Storage"
        CUSTOM_API = "CUSTOM_API", "External Integration API"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, null=True, blank=True, related_name="integration_keys"
    )
    name = models.CharField(max_length=120)
    service_type = models.CharField(max_length=20, choices=ServiceType.choices, default=ServiceType.CUSTOM_API)
    endpoint_url = models.CharField(max_length=300, blank=True)
    key_prefix = models.CharField(max_length=16, db_index=True)
    secret_hash = models.CharField(max_length=128)
    secret_encrypted = models.TextField(blank=True)
    scopes = models.JSONField(default=list, blank=True)
    is_active = models.BooleanField(default=True)
    expires_at = models.DateTimeField(null=True, blank=True)
    last_used_at = models.DateTimeField(null=True, blank=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]


class SecurityLoginEvent(models.Model):
    class EventType(models.TextChoices):
        LOGIN_SUCCESS = "LOGIN_SUCCESS", "Login Success"
        LOGIN_FAILED = "LOGIN_FAILED", "Login Failed"
        LOCKOUT = "LOCKOUT", "Account Locked Out"
        LOGOUT = "LOGOUT", "Logout"
        MFA_FAIL = "MFA_FAIL", "MFA Verification Failed"
        SESSION_REVOKED = "SESSION_REVOKED", "Session / Device Revoked"
        IP_BLOCKED = "IP_BLOCKED", "IP Allowlist Blocked"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="security_events"
    )
    username_attempted = models.CharField(max_length=150, db_index=True)
    event_type = models.CharField(max_length=24, choices=EventType.choices, db_index=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    user_agent = models.CharField(max_length=255, blank=True)
    device_id = models.CharField(max_length=128, blank=True)
    failure_reason = models.CharField(max_length=255, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ["-created_at"]


class CriticalOperationRequest(models.Model):
    class OperationType(models.TextChoices):
        RESTORE_EXECUTE = "RESTORE_EXECUTE", "Database / System Restore"
        SOFTWARE_UPGRADE = "SOFTWARE_UPGRADE", "Software Upgrade"
        SOFTWARE_ROLLBACK = "SOFTWARE_ROLLBACK", "Software Rollback"
        SUPER_ADMIN_GRANT = "SUPER_ADMIN_GRANT", "Super Admin Grant"
        COMPANY_DEACTIVATE = "COMPANY_DEACTIVATE", "Company Deactivate"

    class Status(models.TextChoices):
        PENDING = "PENDING", "Pending Second Approval"
        APPROVED = "APPROVED", "Approved"
        REJECTED = "REJECTED", "Rejected"
        EXECUTED = "EXECUTED", "Executed"
        EXPIRED = "EXPIRED", "Expired"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    operation_type = models.CharField(max_length=28, choices=OperationType.choices, db_index=True)
    target_ref = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    reason = models.TextField(blank=True)
    requested_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="critical_requests"
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="critical_approvals"
    )
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING, db_index=True)
    decision_note = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    decided_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["-created_at"]

