import hashlib
import logging
import uuid

from django.contrib.auth import get_user_model
from django.contrib.auth.models import AbstractUser
from django.core.exceptions import ValidationError
from django.db import models

from core.clients import transport
from core.lib.notify import raw_sendmsg

logger = logging.getLogger(__name__)

SERVICE_CHOICES = (
    ("signal", "Signal"),
    ("whatsapp", "WhatsApp"),
    ("xmpp", "XMPP"),
    ("instagram", "Instagram"),
)
CHANNEL_SERVICE_CHOICES = SERVICE_CHOICES + (("web", "Web"),)
MBTI_CHOICES = (
    ("INTJ", "INTJ - Architect"),  # ;)
    ("INTP", "INTP - Logician"),
    ("ENTJ", "ENTJ - Commander"),
    ("ENTP", "ENTP - Debater"),
    ("INFJ", "INFJ - Advocate"),
    ("INFP", "INFP - Mediator"),
    ("ENFJ", "ENFJ - Protagonist"),
    ("ENFP", "ENFP - Campaigner"),  # <3
    ("ISTJ", "ISTJ - Logistician"),
    ("ISFJ", "ISFJ - Defender"),
    ("ESTJ", "ESTJ - Executive"),
    ("ESFJ", "ESFJ - Consul"),
    ("ISTP", "ISTP - Virtuoso"),
    ("ISFP", "ISFP - Adventurer"),
    ("ESTP", "ESTP - Entrepreneur"),
    ("ESFP", "ESFP - Entertainer"),
)

MODEL_CHOICES = (
    ("gpt-4o-mini", "GPT 4o Mini"),
    ("gpt-4o", "GPT 4o"),
)


def _attribute_display_id(kind, *parts):
    """
    Build a deterministic short display id from object attributes.

    Format:
    - 3 lowercase letters
    - 4 fixed digits
    Example: `kqa1042`
    """
    raw = "|".join([kind, *[str(part or "") for part in parts]])
    digest = hashlib.sha1(raw.encode("utf-8")).hexdigest()

    n_letters = int(digest[:8], 16)
    letters = []
    for _ in range(3):
        letters.append(chr(ord("a") + (n_letters % 26)))
        n_letters //= 26

    digits = int(digest[8:16], 16) % 10000
    return f"{''.join(letters)}{str(digits).zfill(4)}"


def get_default_workspace_user_pk():
    """
    Fallback owner used when adding non-null `user` FKs to existing rows.
    """
    user_pk = (
        get_user_model().objects.order_by("id").values_list("id", flat=True).first()
    )
    return user_pk or 1


class User(AbstractUser):
    # Stripe customer ID
    stripe_id = models.CharField(max_length=255, null=True, blank=True)
    customer_id = models.UUIDField(default=uuid.uuid4, null=True, blank=True)
    billing_provider_id = models.CharField(max_length=255, null=True, blank=True)
    email = models.EmailField(unique=True)
    allow_contacts_to_create_tasks = models.BooleanField(default=True)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._original = self

    def get_notification_settings(self):
        return NotificationSettings.objects.get_or_create(user=self)[0]

    def sendmsg(self, *args, **kwargs):
        notification_settings = self.get_notification_settings()

        if notification_settings.ntfy_topic is None:
            # No topic set, so don't send
            return
        else:
            topic = notification_settings.ntfy_topic

        raw_sendmsg(*args, **kwargs, url=notification_settings.ntfy_url, topic=topic)


class NotificationSettings(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    ntfy_topic = models.CharField(max_length=255, null=True, blank=True)
    ntfy_url = models.CharField(max_length=255, null=True, blank=True)

    def __str__(self):
        return f"Notification settings for {self.user}"


class Chat(models.Model):
    source_number = models.CharField(max_length=32, null=True, blank=True)
    source_uuid = models.CharField(max_length=255, null=True, blank=True)
    source_name = models.CharField(max_length=255, null=True, blank=True)
    account = models.CharField(max_length=32, null=True, blank=True)


class AI(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    base_url = models.CharField(max_length=255, null=True, blank=True)
    api_key = models.CharField(max_length=255, null=True, blank=True)
    model = models.CharField(max_length=255, choices=MODEL_CHOICES)

    def __str__(self):
        return f"{self.id} - {self.model}"


class AIRunLog(models.Model):
    STATUS_CHOICES = (
        ("running", "Running"),
        ("ok", "OK"),
        ("failed", "Failed"),
    )

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ai_run_logs")
    ai = models.ForeignKey(
        AI,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="run_logs",
    )
    operation = models.CharField(max_length=64, blank=True, default="")
    model = models.CharField(max_length=255, blank=True, default="")
    base_url = models.CharField(max_length=255, blank=True, default="")
    status = models.CharField(max_length=16, choices=STATUS_CHOICES, default="running")
    message_count = models.PositiveIntegerField(default=0)
    prompt_chars = models.PositiveIntegerField(default=0)
    response_chars = models.PositiveIntegerField(default=0)
    error = models.TextField(blank=True, default="")
    started_at = models.DateTimeField(auto_now_add=True)
    finished_at = models.DateTimeField(null=True, blank=True)
    duration_ms = models.PositiveIntegerField(null=True, blank=True)

    class Meta:
        indexes = [
            models.Index(fields=["user", "started_at"]),
            models.Index(fields=["user", "status", "started_at"]),
            models.Index(fields=["user", "operation", "started_at"]),
            models.Index(fields=["user", "model", "started_at"]),
        ]


class Person(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    summary = models.TextField(blank=True, null=True)
    profile = models.TextField(blank=True, null=True)

    revealed = models.TextField(blank=True, null=True)

    dislikes = models.TextField(blank=True, null=True)
    likes = models.TextField(blank=True, null=True)

    # -1 (disliked) to +1 (trusted)
    sentiment = models.FloatField(default=0.0)
    timezone = models.CharField(max_length=50, blank=True, null=True)

    last_interaction = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.name


class PersonIdentifier(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    identifier = models.CharField(max_length=255)
    service = models.CharField(choices=SERVICE_CHOICES, max_length=255)
    person = models.ForeignKey(Person, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.person} ({self.service})"

    async def send(self, text, attachments=None, metadata=None):
        """
        Send this contact a text.
        """
        return await transport.send_message_raw(
            self.service,
            self.identifier,
            text=text,
            attachments=attachments or [],
            metadata=dict(metadata or {}),
        )


class PlatformChatLink(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    person = models.ForeignKey(Person, on_delete=models.CASCADE, null=True, blank=True)
    person_identifier = models.ForeignKey(
        PersonIdentifier,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    service = models.CharField(choices=SERVICE_CHOICES, max_length=255)
    chat_identifier = models.CharField(max_length=255)
    chat_jid = models.CharField(max_length=255, blank=True, null=True)
    chat_name = models.CharField(max_length=255, blank=True, null=True)
    is_group = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["user", "service", "chat_identifier"],
                name="unique_platform_chat_link",
            )
        ]
        indexes = [
            models.Index(fields=["user", "service", "chat_identifier"]),
        ]

    def clean(self):
        if self.person_id and self.user_id and self.person.user_id != self.user_id:
            raise ValidationError("Person must belong to the same user.")
        if self.person_identifier_id:
            if self.person_identifier.user_id != self.user_id:
                raise ValidationError("Person identifier must belong to the same user.")
            if self.person_identifier.person_id != self.person_id:
                raise ValidationError(
                    "Person identifier must belong to the selected person."
                )
            if self.person_identifier.service != self.service:
                raise ValidationError("Chat links cannot be linked across platforms.")

    def save(self, *args, **kwargs):
        value = str(self.chat_identifier or "").strip()
        if "@" in value:
            value = value.split("@", 1)[0]
        self.chat_identifier = value
        self.full_clean()
        return super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.person.name if self.person_id else self.chat_name or self.chat_identifier} ({self.service}: {self.chat_identifier})"


class ChatSession(models.Model):
    """Represents an ongoing chat session for persisted message history."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    identifier = models.ForeignKey(PersonIdentifier, on_delete=models.CASCADE)
    last_interaction = models.DateTimeField(blank=True, null=True)
    summary = models.TextField(blank=True, null=True)

    def __str__(self):
        return f"{self.identifier.person.name} ({self.identifier.service})"


class QueuedMessage(models.Model):
    """Stores individual messages linked to a ChatSession."""

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    session = models.ForeignKey(ChatSession, on_delete=models.CASCADE)
    manipulation = models.ForeignKey("core.Manipulation", on_delete=models.CASCADE)
    ts = models.BigIntegerField()  # Use Unix timestamp
    sender_uuid = models.CharField(max_length=255, blank=True, null=True)  # Signal UUID
    text = models.TextField(blank=True, null=True)

    custom_author = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        ordering = ["ts"]


class Message(models.Model):
    """Stores individual messages linked to a ChatSession."""

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    session = models.ForeignKey(ChatSession, on_delete=models.CASCADE)
    ts = models.BigIntegerField()  # Use Unix timestamp
    sender_uuid = models.CharField(max_length=255, blank=True, null=True)  # Signal UUID
    text = models.TextField(blank=True, null=True)

    custom_author = models.CharField(max_length=255, blank=True, null=True)
    delivered_ts = models.BigIntegerField(
        null=True,
        blank=True,
        help_text="Delivery timestamp (unix ms) when known.",
    )
    read_ts = models.BigIntegerField(
        null=True,
        blank=True,
        help_text="Read timestamp (unix ms) when known.",
    )
    read_source_service = models.CharField(
        max_length=255,
        choices=SERVICE_CHOICES,
        null=True,
        blank=True,
        help_text="Service that reported the read receipt.",
    )
    read_by_identifier = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        help_text="Identifier that read this message (service-native value).",
    )
    receipt_payload = models.JSONField(
        default=dict,
        blank=True,
        help_text="Raw normalized delivery/read receipt metadata.",
    )
    source_service = models.CharField(
        max_length=255,
        choices=CHANNEL_SERVICE_CHOICES,
        null=True,
        blank=True,
        help_text="Source service where this message originally appeared.",
    )
    source_message_id = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text="Source service message id when available.",
    )
    source_chat_id = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text="Source service chat or thread identifier when available.",
    )
    reply_to = models.ForeignKey(
        "self",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="reply_children",
        help_text="Resolved local message this message replies to.",
    )
    reply_source_service = models.CharField(
        max_length=255,
        choices=CHANNEL_SERVICE_CHOICES,
        null=True,
        blank=True,
        help_text="Source service for the replied target.",
    )
    reply_source_message_id = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text="Source message id for the replied target.",
    )
    message_meta = models.JSONField(
        default=dict,
        blank=True,
        help_text="Normalized message metadata such as origin tags.",
    )

    class Meta:
        ordering = ["ts"]
        indexes = [
            models.Index(fields=["user", "source_service", "source_message_id"]),
            models.Index(fields=["user", "session", "ts"]),
            models.Index(
                fields=["user", "reply_source_service", "reply_source_message_id"]
            ),
        ]


class ConversationEvent(models.Model):
    EVENT_TYPE_CHOICES = (
        ("message_created", "Message Created"),
        ("message_edited", "Message Edited"),
        ("message_deleted", "Message Deleted"),
        ("reaction_added", "Reaction Added"),
        ("reaction_removed", "Reaction Removed"),
        ("read_receipt", "Read Receipt"),
        ("typing_started", "Typing Started"),
        ("typing_stopped", "Typing Stopped"),
        ("composing_abandoned", "Composing Abandoned"),
        ("presence_available", "Presence Available"),
        ("presence_unavailable", "Presence Unavailable"),
        ("participant_added", "Participant Added"),
        ("participant_removed", "Participant Removed"),
        ("delivery_receipt", "Delivery Receipt"),
    )

    DIRECTION_CHOICES = (
        ("in", "Inbound"),
        ("out", "Outbound"),
        ("system", "System"),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    session = models.ForeignKey(ChatSession, on_delete=models.CASCADE)
    ts = models.BigIntegerField(
        db_index=True,
        help_text="Event timestamp (unix ms).",
    )
    event_type = models.CharField(max_length=64, choices=EVENT_TYPE_CHOICES)
    direction = models.CharField(max_length=16, choices=DIRECTION_CHOICES)
    actor_identifier = models.CharField(max_length=255, blank=True, default="")
    origin_transport = models.CharField(
        max_length=32, blank=True, default="", choices=CHANNEL_SERVICE_CHOICES
    )
    origin_message_id = models.CharField(max_length=255, blank=True, default="")
    origin_chat_id = models.CharField(max_length=255, blank=True, default="")
    payload = models.JSONField(default=dict, blank=True)
    raw_payload = models.JSONField(default=dict, blank=True)
    trace_id = models.CharField(max_length=64, blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["ts", "created_at"]
        indexes = [
            models.Index(fields=["user", "session", "ts"]),
            models.Index(fields=["origin_transport", "origin_message_id"]),
            models.Index(fields=["trace_id"]),
            models.Index(fields=["event_type", "created_at"]),
        ]


class AdapterHealthEvent(models.Model):
    STATUS_CHOICES = (
        ("ok", "OK"),
        ("degraded", "Degraded"),
        ("down", "Down"),
        ("recovering", "Recovering"),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    service = models.CharField(max_length=32, choices=SERVICE_CHOICES)
    status = models.CharField(max_length=32, choices=STATUS_CHOICES)
    reason = models.TextField(blank=True, default="")
    retry_meta = models.JSONField(default=dict, blank=True)
    ts = models.BigIntegerField(
        db_index=True,
        help_text="Health transition timestamp (unix ms).",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-ts", "-created_at"]
        indexes = [
            models.Index(fields=["service", "ts"]),
            models.Index(fields=["status", "created_at"]),
        ]


class Group(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    people = models.ManyToManyField(Person)

    def __str__(self):
        return self.name


class Persona(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    # Core Identity
    # id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    alias = models.CharField(
        max_length=255, blank=True, null=True
    )  # Preferred name or persona alias
    mbti = models.CharField(max_length=255, choices=MBTI_CHOICES, blank=True, null=True)
    # -1: assertive, +1: assertive
    mbti_identity = models.FloatField(default=0.0)

    # Key Behavioral Traits for Chat Responses
    inner_story = models.TextField(
        blank=True, null=True
    )  # Internal philosophy & worldview
    core_values = models.TextField(
        blank=True, null=True
    )  # What drives their decisions & interactions
    communication_style = models.TextField(
        blank=True, null=True
    )  # How they speak & interact
    flirting_style = models.TextField(
        blank=True, null=True
    )  # How they express attraction
    humor_style = models.CharField(
        max_length=50,
        choices=[
            ("dry", "Dry"),
            ("dark", "Dark"),
            ("playful", "Playful"),
            ("teasing", "Teasing"),
            ("sarcastic", "Sarcastic"),
            ("intellectual", "Intellectual"),
        ],
        blank=True,
        null=True,
    )  # Defines their approach to humor

    # Conversational Preferences
    likes = models.TextField(blank=True, null=True)  # Topics they enjoy discussing
    dislikes = models.TextField(blank=True, null=True)  # Topics or behaviors they avoid
    tone = models.CharField(
        max_length=50,
        choices=[
            ("formal", "Formal"),
            ("casual", "Casual"),
            ("witty", "Witty"),
            ("serious", "Serious"),
            ("warm", "Warm"),
            ("detached", "Detached"),
        ],
        blank=True,
        null=True,
    )  # Defines preferred conversational tone

    # Emotional & Strategic Interaction
    response_tactics = models.TextField(
        blank=True, null=True
    )  # How they handle gaslighting, guilt-tripping, etc.
    persuasion_tactics = models.TextField(
        blank=True, null=True
    )  # How they convince others
    boundaries = models.TextField(
        blank=True, null=True
    )  # What they refuse to tolerate in conversations

    trust = models.IntegerField(
        default=50
    )  # Percentage of initial trust given in interactions
    adaptability = models.IntegerField(
        default=70
    )  # How easily they shift tones or styles

    def __str__(self):
        return f"{self.alias} ({self.mbti}) [{self.tone} {self.humor_style}]"


class Manipulation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    # self = models.ForeignKey(Group, on_delete=models.CASCADE)
    ai = models.ForeignKey(AI, on_delete=models.CASCADE)
    persona = models.ForeignKey(Persona, on_delete=models.CASCADE)
    enabled = models.BooleanField(default=False)
    filter_enabled = models.BooleanField(default=False)
    mode = models.CharField(
        max_length=50,
        choices=[
            ("active", "Send replies to messages"),
            ("instant", "Click link to send reply"),
            ("prospective", "Click link to open page"),
            ("notify", "Send notification of ideal reply only"),
            ("mutate", "Change messages sent on XMPP using the persona"),
            ("silent", "Do not generate or send replies"),
        ],
        blank=True,
        null=True,
    )

    def __str__(self):
        return f"{self.name} [{self.group}]"


class WorkspaceConversation(models.Model):
    """
    Canonical conversation workspace used by the UI.

    This is intentionally distinct from ChatSession:
    - ChatSession is operational history for existing manip/reply flows.
    - WorkspaceConversation is analysis/workspace context for AI tooling.

    TODO:
    Identify conversation "active periods" dynamically using observed mutual
    response cadence (global + per-person baseline), rather than fixed windows.
    """

    class StabilityState(models.TextChoices):
        CALIBRATING = "calibrating", "Calibrating"
        STABLE = "stable", "Stable"
        WATCH = "watch", "Watch"
        FRAGILE = "fragile", "Fragile"

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        help_text="Stable identifier for this workspace conversation.",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="workspace_conversations",
        help_text="Owner of this conversation workspace.",
    )
    title = models.CharField(
        max_length=255,
        blank=True,
        default="",
        help_text="Human-friendly label shown in the workspace sidebar.",
    )
    platform_type = models.CharField(
        max_length=255,
        choices=SERVICE_CHOICES,
        default="signal",
        help_text="Primary transport for this conversation (reuses SERVICE_CHOICES).",
    )
    platform_thread_id = models.CharField(
        max_length=255,
        blank=True,
        default="",
        help_text="Platform-native thread/group identifier when available.",
    )
    participants = models.ManyToManyField(
        Person,
        related_name="workspace_conversations",
        blank=True,
        help_text="Resolved people participating in this conversation.",
    )
    participant_feedback = models.JSONField(
        default=dict,
        blank=True,
        help_text=(
            "Per-person interaction feedback map keyed by person UUID. "
            "Example: {'<person_uuid>': {'state': 'withdrawing', 'note': 'short replies'}}."
        ),
    )
    last_event_ts = models.BigIntegerField(
        null=True,
        blank=True,
        help_text="Latest message timestamp (unix ms) currently known.",
    )
    last_ai_run_at = models.DateTimeField(
        null=True,
        blank=True,
        help_text="Last time any AIRequest finished for this conversation.",
    )
    stability_state = models.CharField(
        max_length=32,
        choices=StabilityState.choices,
        default=StabilityState.CALIBRATING,
        help_text="UI label for relationship stability, baseline-aware.",
    )
    stability_score = models.FloatField(
        null=True,
        blank=True,
        help_text="Relationship stability score (0-100). Null while calibrating.",
    )
    stability_confidence = models.FloatField(
        default=0.0,
        help_text="Confidence in stability_score (0.0-1.0).",
    )
    stability_sample_messages = models.PositiveIntegerField(
        default=0,
        help_text="How many messages were used to compute stability.",
    )
    stability_sample_days = models.PositiveIntegerField(
        default=0,
        help_text="How many calendar days of data were used for stability.",
    )
    stability_last_computed_at = models.DateTimeField(
        null=True,
        blank=True,
        help_text="Timestamp of the latest stability computation.",
    )
    commitment_outbound_score = models.FloatField(
        null=True,
        blank=True,
        help_text=(
            "Estimated commitment score for user -> counterpart direction (0-100). "
            "Null while calibrating."
        ),
    )
    commitment_inbound_score = models.FloatField(
        null=True,
        blank=True,
        help_text=(
            "Estimated commitment score for counterpart -> user direction (0-100). "
            "Null while calibrating."
        ),
    )
    commitment_confidence = models.FloatField(
        default=0.0,
        help_text="Confidence in commitment scores (0.0-1.0).",
    )
    commitment_last_computed_at = models.DateTimeField(
        null=True,
        blank=True,
        help_text="Timestamp of the latest commitment computation.",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="Row creation timestamp.",
    )

    def __str__(self):
        return self.title or f"{self.platform_type}:{self.id}"


class WorkspaceMetricSnapshot(models.Model):
    """
    Historical snapshots of workspace metrics for trend visualisation.
    """

    conversation = models.ForeignKey(
        WorkspaceConversation,
        on_delete=models.CASCADE,
        related_name="metric_snapshots",
        help_text="Workspace conversation this metric snapshot belongs to.",
    )
    computed_at = models.DateTimeField(
        auto_now_add=True,
        db_index=True,
        help_text="When this snapshot was persisted.",
    )
    source_event_ts = models.BigIntegerField(
        null=True,
        blank=True,
        help_text="Latest message timestamp used during this metric computation.",
    )
    stability_state = models.CharField(
        max_length=32,
        choices=WorkspaceConversation.StabilityState.choices,
        default=WorkspaceConversation.StabilityState.CALIBRATING,
        help_text="Stability state at computation time.",
    )
    stability_score = models.FloatField(
        null=True,
        blank=True,
        help_text="Stability score (0-100).",
    )
    stability_confidence = models.FloatField(
        default=0.0,
        help_text="Confidence in stability score (0.0-1.0).",
    )
    stability_sample_messages = models.PositiveIntegerField(
        default=0,
        help_text="How many messages were in the sampled window.",
    )
    stability_sample_days = models.PositiveIntegerField(
        default=0,
        help_text="How many days were in the sampled window.",
    )
    commitment_inbound_score = models.FloatField(
        null=True,
        blank=True,
        help_text="Commitment estimate counterpart -> user (0-100).",
    )
    commitment_outbound_score = models.FloatField(
        null=True,
        blank=True,
        help_text="Commitment estimate user -> counterpart (0-100).",
    )
    commitment_confidence = models.FloatField(
        default=0.0,
        help_text="Confidence in commitment scores (0.0-1.0).",
    )
    inbound_messages = models.PositiveIntegerField(
        default=0,
        help_text="Inbound message count in the sampled window.",
    )
    outbound_messages = models.PositiveIntegerField(
        default=0,
        help_text="Outbound message count in the sampled window.",
    )
    reciprocity_score = models.FloatField(
        null=True,
        blank=True,
        help_text="Balance component used for stability.",
    )
    continuity_score = models.FloatField(
        null=True,
        blank=True,
        help_text="Continuity component used for stability.",
    )
    response_score = models.FloatField(
        null=True,
        blank=True,
        help_text="Response-time component used for stability.",
    )
    volatility_score = models.FloatField(
        null=True,
        blank=True,
        help_text="Volatility component used for stability.",
    )
    inbound_response_score = models.FloatField(
        null=True,
        blank=True,
        help_text="Inbound response-lag score used for commitment.",
    )
    outbound_response_score = models.FloatField(
        null=True,
        blank=True,
        help_text="Outbound response-lag score used for commitment.",
    )
    balance_inbound_score = models.FloatField(
        null=True,
        blank=True,
        help_text="Inbound balance score used for commitment.",
    )
    balance_outbound_score = models.FloatField(
        null=True,
        blank=True,
        help_text="Outbound balance score used for commitment.",
    )

    class Meta:
        ordering = ("-computed_at",)
        indexes = [
            models.Index(fields=["conversation", "computed_at"]),
        ]

    def __str__(self):
        return f"Metrics {self.conversation_id} @ {self.computed_at.isoformat()}"


class MessageEvent(models.Model):
    """
    Normalized message event used by workspace timeline and AI selection windows.
    """

    SOURCE_SYSTEM_CHOICES = (
        *SERVICE_CHOICES,
        ("workspace", "Workspace"),
        ("ai", "AI"),
    )

    DIRECTION_CHOICES = (
        ("in", "Inbound"),
        ("out", "Outbound"),
    )

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        help_text="Stable identifier for this message event.",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="workspace_message_events",
        default=get_default_workspace_user_pk,
        help_text=(
            "Owner of this message event row "
            "(required for restricted CRUD filtering)."
        ),
    )
    conversation = models.ForeignKey(
        WorkspaceConversation,
        on_delete=models.CASCADE,
        related_name="events",
        help_text=(
            "AI workspace conversation this message belongs to. "
            "This is not the transport-native thread object."
        ),
    )
    source_system = models.CharField(
        max_length=32,
        choices=SOURCE_SYSTEM_CHOICES,
        default="signal",
        help_text="System that produced this event record.",
    )
    ts = models.BigIntegerField(
        db_index=True,
        help_text="Event timestamp (unix ms) as reported by source_system.",
    )
    direction = models.CharField(
        max_length=8,
        choices=DIRECTION_CHOICES,
        help_text=(
            "Direction relative to workspace owner: "
            "'in' from counterpart(s), 'out' from user/bot side."
        ),
    )
    sender_uuid = models.CharField(
        max_length=255,
        blank=True,
        default="",
        db_index=True,
        help_text="Source sender UUID/identifier for correlation.",
    )
    text = models.TextField(
        blank=True,
        default="",
        help_text="Normalized message text body.",
    )
    attachments = models.JSONField(
        default=list,
        blank=True,
        help_text="Attachment metadata list associated with this message.",
    )
    raw_payload_ref = models.JSONField(
        default=dict,
        blank=True,
        help_text="Raw source payload or reference pointer for audit/debug.",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="Row creation timestamp.",
    )

    class Meta:
        ordering = ["ts"]


class AIRequest(models.Model):
    """
    User-initiated AI run against a selected message window.

    TODO:
    Resolve message window dynamically based on available model context budget
    and content size (chunk-aware), not fixed hard caps.
    """

    STATUS_CHOICES = (
        ("queued", "Queued"),
        ("running", "Running"),
        ("done", "Done"),
        ("failed", "Failed"),
    )

    OPERATION_CHOICES = (
        ("summarise", "Summarise"),
        ("draft_reply", "Draft Reply"),
        ("critique", "Critique"),
        ("repair", "Repair"),
        ("extract_patterns", "Extract Patterns"),
        ("memory_propose", "Memory Propose"),
        ("state_detect", "State Detect"),
        ("rewrite_style", "Rewrite Style"),
        ("send_readiness", "Send Readiness"),
        ("timeline_brief", "Timeline Brief"),
    )

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        help_text="Stable identifier for this AI request.",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="workspace_ai_requests",
        help_text="User who initiated this request.",
    )
    conversation = models.ForeignKey(
        WorkspaceConversation,
        on_delete=models.CASCADE,
        related_name="ai_requests",
        help_text="Conversation analyzed by this request.",
    )
    window_spec = models.JSONField(
        default=dict,
        help_text=(
            "Selection spec (last_n/since_ts/between_ts/include_attachments/etc). "
            "Should be dynamically resolved by available context/token budget."
        ),
    )
    message_ids = models.JSONField(
        default=list,
        blank=True,
        help_text="Resolved ordered MessageEvent IDs included in this run.",
    )
    user_notes = models.TextField(
        blank=True,
        default="",
        help_text="Optional user intent/context notes injected into the prompt.",
    )
    operation = models.CharField(
        max_length=32,
        choices=OPERATION_CHOICES,
        help_text="Requested AI operation type.",
    )
    policy_snapshot = models.JSONField(
        default=dict,
        blank=True,
        help_text=(
            "Effective manipulation/policy values captured at request time, "
            "so results remain auditable even if policies change later."
        ),
    )
    status = models.CharField(
        max_length=16,
        choices=STATUS_CHOICES,
        default="queued",
        help_text="Worker lifecycle state for this request.",
    )
    error = models.TextField(
        blank=True,
        default="",
        help_text="Error details when status='failed'.",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="Request creation timestamp.",
    )
    started_at = models.DateTimeField(
        null=True,
        blank=True,
        help_text="Worker start timestamp.",
    )
    finished_at = models.DateTimeField(
        null=True,
        blank=True,
        help_text="Worker completion timestamp.",
    )


class AIResult(models.Model):
    """
    Persisted output payload for a completed AIRequest.
    """

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        help_text="Stable identifier for this AI result payload.",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="workspace_ai_results",
        default=get_default_workspace_user_pk,
        help_text=(
            "Owner of this AI result row " "(required for restricted CRUD filtering)."
        ),
    )
    ai_request = models.OneToOneField(
        AIRequest,
        on_delete=models.CASCADE,
        related_name="result",
        help_text="Owning AI request for this result.",
    )
    working_summary = models.TextField(
        blank=True,
        default="",
        help_text="Conversation working summary generated for this run.",
    )
    draft_replies = models.JSONField(
        default=list,
        blank=True,
        help_text="Draft reply candidates, typically with tone and rationale.",
    )
    interaction_signals = models.JSONField(
        default=list,
        blank=True,
        help_text=(
            "Structured positive/neutral/risk signals inferred for this run. "
            "Example item: {'label':'repair_attempt','valence':'positive',"
            "'message_event_ids':[...]}."
        ),
    )
    memory_proposals = models.JSONField(
        default=list,
        blank=True,
        help_text="Proposed memory entries, typically requiring user approval.",
    )
    citations = models.JSONField(
        default=list,
        blank=True,
        help_text="Referenced MessageEvent IDs supporting generated claims.",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="Result creation timestamp.",
    )


class MemoryItem(models.Model):
    """
    Durable/semi-durable memory used to provide continuity across AI runs.
    """

    MEMORY_KIND_CHOICES = (
        ("fact", "Durable Fact/Preference"),
        ("state", "Relationship State"),
        ("summary", "Conversation Working Summary"),
    )

    STATUS_CHOICES = (
        ("proposed", "Proposed"),
        ("active", "Active"),
        ("deprecated", "Deprecated"),
    )

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        help_text="Stable identifier for this memory item.",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="workspace_memory_items",
        help_text="Owner of the memory item.",
    )
    conversation = models.ForeignKey(
        WorkspaceConversation,
        on_delete=models.CASCADE,
        related_name="memory_items",
        help_text="Conversation scope this memory item belongs to.",
    )
    person = models.ForeignKey(
        Person,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="memory_items",
        help_text="Optional person this memory is about for person-centric recall.",
    )
    memory_kind = models.CharField(
        max_length=16,
        choices=MEMORY_KIND_CHOICES,
        help_text="Memory kind: fact/state/summary.",
    )
    status = models.CharField(
        max_length=16,
        choices=STATUS_CHOICES,
        default="proposed",
        help_text="Lifecycle state, especially for approval-gated memories.",
    )
    content = models.JSONField(
        default=dict,
        blank=True,
        help_text="Structured memory payload (schema can evolve by type).",
    )
    provenance = models.JSONField(
        default=dict,
        blank=True,
        help_text="Source metadata for this memory (agent/tool/message references).",
    )
    confidence_score = models.FloatField(
        default=0.5,
        help_text="Confidence score for this memory (0.0-1.0).",
    )
    expires_at = models.DateTimeField(
        null=True,
        blank=True,
        help_text="Optional expiry timestamp for stale memory decay.",
    )
    last_verified_at = models.DateTimeField(
        null=True,
        blank=True,
        help_text="Last operator verification timestamp.",
    )
    source_request = models.ForeignKey(
        AIRequest,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        help_text="AIRequest that originated this memory, if any.",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="Row creation timestamp.",
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        help_text="Last update timestamp.",
    )

    class Meta:
        indexes = [
            models.Index(fields=["user", "status", "updated_at"]),
            models.Index(fields=["user", "person", "status", "updated_at"]),
            models.Index(fields=["user", "conversation", "status", "updated_at"]),
        ]


class MemorySourceReference(models.Model):
    memory = models.ForeignKey(
        MemoryItem,
        on_delete=models.CASCADE,
        related_name="source_references",
    )
    message_event = models.ForeignKey(
        "MessageEvent",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="memory_source_references",
    )
    message = models.ForeignKey(
        Message,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="memory_source_references",
    )
    source_request = models.ForeignKey(
        AIRequest,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="memory_source_references",
    )
    source_label = models.CharField(max_length=255, blank=True, default="")
    source_uri = models.CharField(max_length=1024, blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [
            models.Index(fields=["memory", "created_at"]),
            models.Index(fields=["source_uri"]),
        ]


class MemoryChangeRequest(models.Model):
    ACTION_CHOICES = (
        ("create", "Create"),
        ("update", "Update"),
        ("delete", "Delete"),
    )
    STATUS_CHOICES = (
        ("pending", "Pending"),
        ("approved", "Approved"),
        ("rejected", "Rejected"),
        ("applied", "Applied"),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="memory_change_requests",
    )
    memory = models.ForeignKey(
        MemoryItem,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="change_requests",
    )
    conversation = models.ForeignKey(
        WorkspaceConversation,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="memory_change_requests",
    )
    person = models.ForeignKey(
        Person,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="memory_change_requests",
    )
    action = models.CharField(max_length=16, choices=ACTION_CHOICES)
    status = models.CharField(max_length=16, choices=STATUS_CHOICES, default="pending")
    proposed_memory_kind = models.CharField(max_length=16, blank=True, default="")
    proposed_content = models.JSONField(default=dict, blank=True)
    proposed_confidence_score = models.FloatField(null=True, blank=True)
    proposed_expires_at = models.DateTimeField(null=True, blank=True)
    reason = models.TextField(blank=True, default="")
    requested_by_identifier = models.CharField(max_length=255, blank=True, default="")
    reviewed_by_identifier = models.CharField(max_length=255, blank=True, default="")
    reviewed_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [
            models.Index(fields=["user", "status", "created_at"]),
            models.Index(fields=["memory", "created_at"]),
        ]


class AIResultSignal(models.Model):
    """
    Message-linked evidence signal produced by an AIResult.

    This lets the UI point to concrete messages (good or bad) rather than
    generic flags.
    """

    VALENCE_CHOICES = (
        ("positive", "Positive"),
        ("neutral", "Neutral"),
        ("risk", "Risk"),
    )

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        help_text="Stable identifier for this result signal.",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="workspace_ai_result_signals",
        help_text="Owner of this signal row (required for restricted CRUD filtering).",
    )
    ai_result = models.ForeignKey(
        AIResult,
        on_delete=models.CASCADE,
        related_name="signals",
        help_text="AI result that produced this signal.",
    )
    message_event = models.ForeignKey(
        MessageEvent,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="ai_signals",
        help_text="Optional specific message event referenced by this signal.",
    )
    label = models.CharField(
        max_length=128,
        help_text="Short signal label, e.g. 'withdrawing', 'repair_attempt'.",
    )
    valence = models.CharField(
        max_length=16,
        choices=VALENCE_CHOICES,
        default="neutral",
        help_text="Signal polarity: positive, neutral, or risk.",
    )
    score = models.FloatField(
        null=True,
        blank=True,
        help_text="Optional model confidence/strength (0.0-1.0).",
    )
    rationale = models.TextField(
        blank=True,
        default="",
        help_text="Human-readable explanation for this signal.",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="Row creation timestamp.",
    )


class PatternMitigationPlan(models.Model):
    """
    Stores a mitigation plan generated from extracted interaction patterns.

    The plan is the parent container for rules, games, mitigation chat,
    and artifact exports.
    """

    STATUS_CHOICES = (
        ("draft", "Draft"),
        ("active", "Active"),
        ("archived", "Archived"),
    )

    CREATION_MODE_CHOICES = (
        ("auto", "Auto"),
        ("guided", "Guided"),
    )

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        help_text="Stable identifier for this mitigation plan.",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="pattern_mitigation_plans",
        help_text="Owner of this plan.",
    )
    conversation = models.ForeignKey(
        WorkspaceConversation,
        on_delete=models.CASCADE,
        related_name="mitigation_plans",
        help_text="Workspace conversation this plan belongs to.",
    )
    source_ai_result = models.ForeignKey(
        AIResult,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="mitigation_plans",
        help_text="AI result that initiated this plan, if any.",
    )
    title = models.CharField(
        max_length=255,
        blank=True,
        default="",
        help_text="Display title for this plan.",
    )
    objective = models.TextField(
        blank=True,
        default="",
        help_text="High-level objective this plan is meant to achieve.",
    )
    fundamental_items = models.JSONField(
        default=list,
        blank=True,
        help_text="Foundational agreed items/principles for this plan.",
    )
    creation_mode = models.CharField(
        max_length=16,
        choices=CREATION_MODE_CHOICES,
        default="auto",
        help_text="Whether plan artifacts were generated automatically or user-guided.",
    )
    status = models.CharField(
        max_length=16,
        choices=STATUS_CHOICES,
        default="draft",
        help_text="Lifecycle status of the plan.",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="Row creation timestamp.",
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        help_text="Last update timestamp.",
    )


class PatternMitigationRule(models.Model):
    """
    Rule artifact attached to a mitigation plan.
    """

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        help_text="Stable identifier for this rule.",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="pattern_mitigation_rules",
        help_text="Owner of this rule.",
    )
    plan = models.ForeignKey(
        PatternMitigationPlan,
        on_delete=models.CASCADE,
        related_name="rules",
        help_text="Parent mitigation plan.",
    )
    title = models.CharField(
        max_length=255,
        help_text="Rule title.",
    )
    content = models.TextField(
        blank=True,
        default="",
        help_text="Rule definition/details.",
    )
    enabled = models.BooleanField(
        default=True,
        help_text="Whether this rule is currently enabled.",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="Row creation timestamp.",
    )

    @property
    def display_id(self):
        return _attribute_display_id(
            "rule",
            self.plan_id,
            self.title,
            self.content,
            self.enabled,
        )


class PatternMitigationGame(models.Model):
    """
    Game artifact attached to a mitigation plan.
    """

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        help_text="Stable identifier for this game.",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="pattern_mitigation_games",
        help_text="Owner of this game.",
    )
    plan = models.ForeignKey(
        PatternMitigationPlan,
        on_delete=models.CASCADE,
        related_name="games",
        help_text="Parent mitigation plan.",
    )
    title = models.CharField(
        max_length=255,
        help_text="Game title.",
    )
    instructions = models.TextField(
        blank=True,
        default="",
        help_text="Gameplay/instruction text.",
    )
    enabled = models.BooleanField(
        default=True,
        help_text="Whether this game is currently enabled.",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="Row creation timestamp.",
    )

    @property
    def display_id(self):
        return _attribute_display_id(
            "game",
            self.plan_id,
            self.title,
            self.instructions,
            self.enabled,
        )


class PatternMitigationCorrection(models.Model):
    """
    Shared clarification artifact used to prevent circular misunderstandings.
    """

    PERSPECTIVE_CHOICES = (
        ("third_person", "Third Person"),
        ("second_person", "Second Person"),
        ("first_person", "First Person"),
    )
    SHARE_TARGET_CHOICES = (
        ("self", "Self"),
        ("other", "Other Party"),
        ("both", "Both Parties"),
    )
    LANGUAGE_STYLE_CHOICES = (
        ("same", "Same Language"),
        ("adapted", "Adapted Language"),
    )

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        help_text="Stable identifier for this correction item.",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="pattern_mitigation_corrections",
        help_text="Owner of this correction item.",
    )
    plan = models.ForeignKey(
        PatternMitigationPlan,
        on_delete=models.CASCADE,
        related_name="corrections",
        help_text="Parent mitigation plan.",
    )
    title = models.CharField(
        max_length=255,
        help_text="Correction title. Example: 'Assumption vs intent mismatch'.",
    )
    clarification = models.TextField(
        blank=True,
        default="",
        help_text=(
            "Joint clarification text intended to reduce interpretation drift. "
            'Example: \'When you say "you ignore me", I hear fear of '
            "disconnection, not blame.'"
        ),
    )
    source_phrase = models.TextField(
        blank=True,
        default="",
        help_text=(
            "Situation/message fragment this correction responds to. "
            "Example: 'she says: \"you never listen\"' or "
            "'you say: \"you are dismissing me\"'."
        ),
    )
    perspective = models.CharField(
        max_length=32,
        choices=PERSPECTIVE_CHOICES,
        default="third_person",
        help_text=(
            "Narrative perspective used when framing this correction. "
            "Examples: third person ('she says'), second person ('you say'), "
            "first person ('I say')."
        ),
    )
    share_target = models.CharField(
        max_length=16,
        choices=SHARE_TARGET_CHOICES,
        default="both",
        help_text=(
            "Who this insight is intended to be shared with. "
            "Example: self, other, or both."
        ),
    )
    language_style = models.CharField(
        max_length=16,
        choices=LANGUAGE_STYLE_CHOICES,
        default="adapted",
        help_text=(
            "Whether to keep wording identical or adapt it per recipient. "
            "Example: same text for both parties, or softened/adapted wording "
            "for recipient."
        ),
    )
    enabled = models.BooleanField(
        default=True,
        help_text="Whether this correction item is currently enabled.",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="Row creation timestamp.",
    )

    @property
    def display_id(self):
        return _attribute_display_id(
            "correction",
            self.plan_id,
            self.title,
            self.source_phrase,
            self.clarification,
            self.perspective,
            self.share_target,
            self.language_style,
            self.enabled,
        )


class PatternMitigationMessage(models.Model):
    """
    Conversation log between user and AI within a mitigation plan.
    """

    ROLE_CHOICES = (
        ("user", "User"),
        ("assistant", "Assistant"),
        ("system", "System"),
    )

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        help_text="Stable identifier for this mitigation message.",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="pattern_mitigation_messages",
        help_text="Owner of this message.",
    )
    plan = models.ForeignKey(
        PatternMitigationPlan,
        on_delete=models.CASCADE,
        related_name="messages",
        help_text="Parent mitigation plan.",
    )
    role = models.CharField(
        max_length=16,
        choices=ROLE_CHOICES,
        help_text="Message speaker role.",
    )
    text = models.TextField(
        help_text="Message content.",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="Row creation timestamp.",
    )

    class Meta:
        ordering = ["created_at"]


class PatternMitigationAutoSettings(models.Model):
    """
    Automation controls for mitigation analysis in a workspace conversation.

    These settings let the user enable periodic/triggered checks for pattern
    violations, optional correction creation, and optional notifications.
    """

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        help_text="Stable identifier for this automation settings row.",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="pattern_mitigation_auto_settings",
        help_text="Owner of this automation settings row.",
    )
    conversation = models.OneToOneField(
        WorkspaceConversation,
        on_delete=models.CASCADE,
        related_name="mitigation_auto_settings",
        help_text="Conversation scope this automation config applies to.",
    )
    enabled = models.BooleanField(
        default=False,
        help_text="Master toggle for mitigation automation in this conversation.",
    )
    auto_pattern_recognition = models.BooleanField(
        default=True,
        help_text="Run pattern/violation recognition automatically when triggered.",
    )
    auto_create_mitigation = models.BooleanField(
        default=False,
        help_text="Create a baseline mitigation plan automatically when missing.",
    )
    auto_create_corrections = models.BooleanField(
        default=False,
        help_text="Create correction items automatically from detected violations.",
    )
    auto_notify_enabled = models.BooleanField(
        default=False,
        help_text="Send NTFY notifications when new violations are detected.",
    )
    ntfy_topic_override = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text="Optional NTFY topic override for automation notifications.",
    )
    ntfy_url_override = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text="Optional NTFY server URL override for automation notifications.",
    )
    sample_message_window = models.PositiveIntegerField(
        default=40,
        help_text="How many recent messages to include in each automation check.",
    )
    check_cooldown_seconds = models.PositiveIntegerField(
        default=300,
        help_text="Minimum seconds between automatic checks for this conversation.",
    )
    last_checked_event_ts = models.BigIntegerField(
        null=True,
        blank=True,
        help_text="Latest source message timestamp included in automation checks.",
    )
    last_run_at = models.DateTimeField(
        null=True,
        blank=True,
        help_text="Timestamp when automation last ran.",
    )
    last_result_summary = models.TextField(
        blank=True,
        default="",
        help_text="Human-readable summary from the last automation run.",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="Row creation timestamp.",
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        help_text="Last update timestamp.",
    )

    def __str__(self):
        return f"Auto settings for {self.conversation_id}"


class PatternArtifactExport(models.Model):
    """
    Export protocol record for rules/games/rulebooks generated from a plan.
    """

    ARTIFACT_TYPE_CHOICES = (
        ("rulebook", "Rulebook"),
        ("rules", "Rules"),
        ("games", "Games"),
        ("corrections", "Corrections"),
    )

    FORMAT_CHOICES = (
        ("markdown", "Markdown"),
        ("json", "JSON"),
        ("text", "Text"),
    )

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        help_text="Stable identifier for this export artifact.",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="pattern_artifact_exports",
        help_text="Owner of this export artifact.",
    )
    plan = models.ForeignKey(
        PatternMitigationPlan,
        on_delete=models.CASCADE,
        related_name="exports",
        help_text="Source mitigation plan.",
    )
    artifact_type = models.CharField(
        max_length=32,
        choices=ARTIFACT_TYPE_CHOICES,
        help_text="Artifact category being exported.",
    )
    export_format = models.CharField(
        max_length=16,
        choices=FORMAT_CHOICES,
        default="markdown",
        help_text="Serialized output format.",
    )
    protocol_version = models.CharField(
        max_length=32,
        default="artifact-v1",
        help_text="Artifact export protocol version.",
    )
    payload = models.TextField(
        blank=True,
        default="",
        help_text="Serialized artifact body/content.",
    )
    meta = models.JSONField(
        default=dict,
        blank=True,
        help_text="Additional export metadata (counts, hints, source IDs).",
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="Row creation timestamp.",
    )


class CommandProfile(models.Model):
    WINDOW_SCOPE_CHOICES = (("conversation", "Conversation"),)
    VISIBILITY_CHOICES = (
        ("status_in_source", "Status In Source"),
        ("silent", "Silent"),
    )

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    slug = models.CharField(max_length=64, default="bp")
    name = models.CharField(max_length=255, default="Business Plan")
    enabled = models.BooleanField(default=True)
    trigger_token = models.CharField(max_length=64, default="#bp#")
    reply_required = models.BooleanField(default=True)
    exact_match_only = models.BooleanField(default=True)
    window_scope = models.CharField(
        max_length=64,
        choices=WINDOW_SCOPE_CHOICES,
        default="conversation",
    )
    template_text = models.TextField(blank=True, default="")
    visibility_mode = models.CharField(
        max_length=64,
        choices=VISIBILITY_CHOICES,
        default="status_in_source",
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["user", "slug"],
                name="unique_command_profile_per_user",
            )
        ]

    def __str__(self):
        return f"{self.user_id}:{self.slug}"


class CommandChannelBinding(models.Model):
    DIRECTION_CHOICES = (
        ("ingress", "Ingress"),
        ("egress", "Egress"),
        ("scratchpad_mirror", "Scratchpad Mirror"),
    )

    profile = models.ForeignKey(
        CommandProfile,
        on_delete=models.CASCADE,
        related_name="channel_bindings",
    )
    direction = models.CharField(max_length=64, choices=DIRECTION_CHOICES)
    service = models.CharField(max_length=255, choices=CHANNEL_SERVICE_CHOICES)
    channel_identifier = models.CharField(max_length=255)
    enabled = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [
            models.Index(fields=["profile", "direction", "service"]),
            models.Index(fields=["profile", "service", "channel_identifier"]),
        ]


class CommandVariantPolicy(models.Model):
    GENERATION_MODE_CHOICES = (
        ("ai", "AI"),
        ("verbatim", "Verbatim"),
    )

    profile = models.ForeignKey(
        CommandProfile,
        on_delete=models.CASCADE,
        related_name="variant_policies",
    )
    variant_key = models.CharField(max_length=64, default="default")
    enabled = models.BooleanField(default=True)
    generation_mode = models.CharField(
        max_length=32,
        choices=GENERATION_MODE_CHOICES,
        default="verbatim",
    )
    send_plan_to_egress = models.BooleanField(default=True)
    send_status_to_source = models.BooleanField(default=True)
    send_status_to_egress = models.BooleanField(default=False)
    store_document = models.BooleanField(default=True)
    position = models.PositiveIntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["position", "id"]
        constraints = [
            models.UniqueConstraint(
                fields=["profile", "variant_key"],
                name="unique_command_variant_policy_per_profile",
            )
        ]
        indexes = [
            models.Index(fields=["profile", "enabled", "variant_key"]),
        ]


class CommandAction(models.Model):
    ACTION_CHOICES = (
        ("extract_bp", "Extract Business Plan"),
        ("post_result", "Post Result"),
        ("save_document", "Save Document"),
    )

    profile = models.ForeignKey(
        CommandProfile,
        on_delete=models.CASCADE,
        related_name="actions",
    )
    action_type = models.CharField(max_length=64, choices=ACTION_CHOICES)
    enabled = models.BooleanField(default=True)
    config = models.JSONField(default=dict, blank=True)
    position = models.PositiveIntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["position", "id"]
        indexes = [models.Index(fields=["profile", "action_type", "enabled"])]


class BusinessPlanDocument(models.Model):
    STATUS_CHOICES = (
        ("draft", "Draft"),
        ("final", "Final"),
    )

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    command_profile = models.ForeignKey(
        CommandProfile,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="business_plan_documents",
    )
    source_service = models.CharField(max_length=255, choices=CHANNEL_SERVICE_CHOICES)
    source_channel_identifier = models.CharField(max_length=255, blank=True, default="")
    trigger_message = models.ForeignKey(
        Message,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="business_plan_trigger_docs",
    )
    anchor_message = models.ForeignKey(
        Message,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="business_plan_anchor_docs",
    )
    title = models.CharField(max_length=255, default="Business Plan")
    status = models.CharField(max_length=32, choices=STATUS_CHOICES, default="draft")
    content_markdown = models.TextField(blank=True, default="")
    structured_payload = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [
            models.Index(fields=["user", "status", "updated_at"]),
            models.Index(
                fields=["user", "source_service", "source_channel_identifier"]
            ),
        ]


class BusinessPlanRevision(models.Model):
    document = models.ForeignKey(
        BusinessPlanDocument,
        on_delete=models.CASCADE,
        related_name="revisions",
    )
    editor_user = models.ForeignKey(User, on_delete=models.CASCADE)
    content_markdown = models.TextField(blank=True, default="")
    structured_payload = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["created_at"]


class CommandRun(models.Model):
    STATUS_CHOICES = (
        ("pending", "Pending"),
        ("running", "Running"),
        ("ok", "OK"),
        ("failed", "Failed"),
        ("skipped", "Skipped"),
    )

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    profile = models.ForeignKey(
        CommandProfile,
        on_delete=models.CASCADE,
        related_name="runs",
    )
    trigger_message = models.ForeignKey(
        Message,
        on_delete=models.CASCADE,
        related_name="command_runs",
    )
    status = models.CharField(max_length=32, choices=STATUS_CHOICES, default="pending")
    error = models.TextField(blank=True, default="")
    result_ref = models.ForeignKey(
        BusinessPlanDocument,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="command_runs",
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["profile", "trigger_message"],
                name="unique_command_run_profile_trigger_message",
            )
        ]
        indexes = [models.Index(fields=["user", "status", "updated_at"])]


class CommandSecurityPolicy(models.Model):
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="command_security_policies",
    )
    scope_key = models.CharField(max_length=64, default="gateway.tasks")
    enabled = models.BooleanField(default=True)
    require_omemo = models.BooleanField(default=False)
    require_trusted_omemo_fingerprint = models.BooleanField(default=False)
    allowed_services = models.JSONField(default=list, blank=True)
    allowed_channels = models.JSONField(default=dict, blank=True)
    settings = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["user", "scope_key"],
                name="unique_command_security_policy_per_scope",
            )
        ]
        indexes = [
            models.Index(fields=["user", "scope_key"]),
            models.Index(fields=["user", "enabled", "updated_at"]),
        ]


class GatewayCommandEvent(models.Model):
    STATUS_CHOICES = (
        ("pending", "Pending"),
        ("blocked", "Blocked"),
        ("ok", "OK"),
        ("failed", "Failed"),
        ("ignored", "Ignored"),
    )

    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="gateway_command_events",
    )
    source_message = models.ForeignKey(
        Message,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="gateway_command_events",
    )
    service = models.CharField(max_length=255, choices=CHANNEL_SERVICE_CHOICES)
    channel_identifier = models.CharField(max_length=255, blank=True, default="")
    sender_identifier = models.CharField(max_length=255, blank=True, default="")
    scope_key = models.CharField(max_length=64, blank=True, default="")
    command_name = models.CharField(max_length=64, blank=True, default="")
    command_text = models.TextField(blank=True, default="")
    status = models.CharField(max_length=32, choices=STATUS_CHOICES, default="pending")
    error = models.TextField(blank=True, default="")
    request_meta = models.JSONField(default=dict, blank=True)
    response_meta = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [
            models.Index(fields=["user", "scope_key", "created_at"]),
            models.Index(fields=["user", "status", "created_at"]),
        ]


class TranslationBridge(models.Model):
    DIRECTION_CHOICES = (
        ("a_to_b", "A To B"),
        ("b_to_a", "B To A"),
        ("bidirectional", "Bidirectional"),
    )

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=255, default="Translation Bridge")
    enabled = models.BooleanField(default=True)
    a_service = models.CharField(max_length=255, choices=CHANNEL_SERVICE_CHOICES)
    a_channel_identifier = models.CharField(max_length=255)
    a_language = models.CharField(max_length=64, default="en")
    b_service = models.CharField(max_length=255, choices=CHANNEL_SERVICE_CHOICES)
    b_channel_identifier = models.CharField(max_length=255)
    b_language = models.CharField(max_length=64, default="en")
    direction = models.CharField(
        max_length=32,
        choices=DIRECTION_CHOICES,
        default="bidirectional",
    )
    quick_mode_title = models.CharField(max_length=255, blank=True, default="")
    settings = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [
            models.Index(fields=["user", "enabled"]),
            models.Index(fields=["user", "a_service", "a_channel_identifier"]),
            models.Index(fields=["user", "b_service", "b_channel_identifier"]),
        ]


class TranslationEventLog(models.Model):
    STATUS_CHOICES = (
        ("pending", "Pending"),
        ("ok", "OK"),
        ("failed", "Failed"),
        ("skipped", "Skipped"),
    )

    bridge = models.ForeignKey(
        TranslationBridge,
        on_delete=models.CASCADE,
        related_name="events",
    )
    source_message = models.ForeignKey(
        Message,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="translation_events",
    )
    target_service = models.CharField(max_length=255, choices=CHANNEL_SERVICE_CHOICES)
    target_channel = models.CharField(max_length=255)
    status = models.CharField(max_length=32, choices=STATUS_CHOICES, default="pending")
    error = models.TextField(blank=True, default="")
    origin_tag = models.CharField(max_length=255, blank=True, default="")
    content_hash = models.CharField(max_length=255, blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [
            models.Index(fields=["bridge", "created_at"]),
            models.Index(fields=["bridge", "status", "updated_at"]),
            models.Index(fields=["origin_tag"]),
        ]


class AnswerMemory(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="answer_memory"
    )
    service = models.CharField(max_length=255, choices=CHANNEL_SERVICE_CHOICES)
    channel_identifier = models.CharField(max_length=255)
    question_fingerprint = models.CharField(max_length=128)
    question_text = models.TextField(blank=True, default="")
    answer_message = models.ForeignKey(
        Message,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="answer_memory_rows",
    )
    answer_text = models.TextField(blank=True, default="")
    confidence_meta = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [
            models.Index(
                fields=["user", "service", "channel_identifier", "created_at"]
            ),
            models.Index(fields=["user", "question_fingerprint", "created_at"]),
        ]


class AnswerSuggestionEvent(models.Model):
    STATUS_CHOICES = (
        ("suggested", "Suggested"),
        ("accepted", "Accepted"),
        ("dismissed", "Dismissed"),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="answer_suggestion_events",
    )
    message = models.ForeignKey(
        Message,
        on_delete=models.CASCADE,
        related_name="answer_suggestion_events",
    )
    status = models.CharField(
        max_length=32, choices=STATUS_CHOICES, default="suggested"
    )
    candidate_answer = models.ForeignKey(
        AnswerMemory,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="suggestion_events",
    )
    score = models.FloatField(default=0.0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [
            models.Index(fields=["user", "status", "created_at"]),
            models.Index(fields=["message", "status"]),
        ]


class TaskProject(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="task_projects"
    )
    name = models.CharField(max_length=255)
    external_key = models.CharField(max_length=255, blank=True, default="")
    active = models.BooleanField(default=True)
    settings = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["user", "name"],
                name="unique_task_project_name_per_user",
            )
        ]
        indexes = [models.Index(fields=["user", "active", "updated_at"])]


class TaskEpic(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    project = models.ForeignKey(
        TaskProject,
        on_delete=models.CASCADE,
        related_name="epics",
    )
    name = models.CharField(max_length=255)
    external_key = models.CharField(max_length=255, blank=True, default="")
    active = models.BooleanField(default=True)
    settings = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["project", "name"],
                name="unique_task_epic_name_per_project",
            )
        ]
        indexes = [models.Index(fields=["project", "active", "updated_at"])]


class ChatTaskSource(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="chat_task_sources"
    )
    service = models.CharField(max_length=255, choices=CHANNEL_SERVICE_CHOICES)
    channel_identifier = models.CharField(max_length=255)
    project = models.ForeignKey(
        TaskProject,
        on_delete=models.CASCADE,
        related_name="chat_sources",
    )
    epic = models.ForeignKey(
        TaskEpic,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="chat_sources",
    )
    enabled = models.BooleanField(default=True)
    settings = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [
            models.Index(fields=["user", "service", "channel_identifier", "enabled"]),
            models.Index(fields=["project", "enabled"]),
        ]


class DerivedTask(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="derived_tasks"
    )
    project = models.ForeignKey(
        TaskProject,
        on_delete=models.CASCADE,
        related_name="derived_tasks",
    )
    epic = models.ForeignKey(
        TaskEpic,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="derived_tasks",
    )
    title = models.CharField(max_length=255)
    source_service = models.CharField(max_length=255, choices=CHANNEL_SERVICE_CHOICES)
    source_channel = models.CharField(max_length=255)
    origin_message = models.ForeignKey(
        Message,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="derived_task_origins",
    )
    reference_code = models.CharField(max_length=64, blank=True, default="")
    external_key = models.CharField(max_length=255, blank=True, default="")
    status_snapshot = models.CharField(max_length=64, blank=True, default="open")
    due_date = models.DateField(null=True, blank=True)
    assignee_identifier = models.CharField(max_length=255, blank=True, default="")
    immutable_payload = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [
            models.Index(fields=["user", "project", "created_at"]),
            models.Index(fields=["user", "source_service", "source_channel"]),
            models.Index(fields=["user", "reference_code"]),
        ]


class DerivedTaskEvent(models.Model):
    EVENT_CHOICES = (
        ("created", "Created"),
        ("progress", "Progress"),
        ("completion_marked", "Completion Marked"),
        ("synced", "Synced"),
        ("sync_failed", "Sync Failed"),
        ("parse_warning", "Parse Warning"),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    task = models.ForeignKey(
        DerivedTask,
        on_delete=models.CASCADE,
        related_name="events",
    )
    event_type = models.CharField(max_length=32, choices=EVENT_CHOICES)
    actor_identifier = models.CharField(max_length=255, blank=True, default="")
    source_message = models.ForeignKey(
        Message,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="derived_task_events",
    )
    payload = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["created_at", "id"]
        indexes = [
            models.Index(fields=["task", "created_at"]),
            models.Index(fields=["event_type", "created_at"]),
        ]


class TaskArtifactLink(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    task = models.ForeignKey(
        DerivedTask,
        on_delete=models.CASCADE,
        related_name="artifact_links",
    )
    kind = models.CharField(max_length=64, default="note")
    uri = models.CharField(max_length=1024, blank=True, default="")
    path = models.CharField(max_length=1024, blank=True, default="")
    summary = models.TextField(blank=True, default="")
    created_by_identifier = models.CharField(max_length=255, blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [
            models.Index(fields=["task", "created_at"]),
            models.Index(fields=["kind", "created_at"]),
        ]


class KnowledgeArticle(models.Model):
    STATUS_CHOICES = (
        ("draft", "Draft"),
        ("published", "Published"),
        ("archived", "Archived"),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="knowledge_articles",
    )
    related_task = models.ForeignKey(
        DerivedTask,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="knowledge_articles",
    )
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255)
    markdown = models.TextField(blank=True, default="")
    tags = models.JSONField(default=list, blank=True)
    status = models.CharField(max_length=16, choices=STATUS_CHOICES, default="draft")
    owner_identifier = models.CharField(max_length=255, blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["user", "slug"],
                name="unique_knowledge_article_slug_per_user",
            ),
        ]
        indexes = [
            models.Index(fields=["user", "status", "updated_at"]),
            models.Index(fields=["related_task", "updated_at"]),
        ]


class KnowledgeRevision(models.Model):
    article = models.ForeignKey(
        KnowledgeArticle,
        on_delete=models.CASCADE,
        related_name="revisions",
    )
    revision = models.PositiveIntegerField()
    author_tool = models.CharField(max_length=255, blank=True, default="")
    author_identifier = models.CharField(max_length=255, blank=True, default="")
    summary = models.TextField(blank=True, default="")
    markdown = models.TextField(blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["article", "revision"],
                name="unique_knowledge_revision_per_article",
            )
        ]
        ordering = ["article", "revision"]


class MCPToolAuditLog(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    tool_name = models.CharField(max_length=255)
    user = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="mcp_tool_audit_logs",
    )
    request_args = models.JSONField(default=dict, blank=True)
    response_meta = models.JSONField(default=dict, blank=True)
    ok = models.BooleanField(default=True)
    error = models.TextField(blank=True, default="")
    duration_ms = models.PositiveIntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [
            models.Index(fields=["tool_name", "created_at"]),
            models.Index(fields=["user", "created_at"]),
            models.Index(fields=["ok", "created_at"]),
        ]


class ExternalSyncEvent(models.Model):
    STATUS_CHOICES = (
        ("pending", "Pending"),
        ("ok", "OK"),
        ("failed", "Failed"),
        ("retrying", "Retrying"),
        ("waiting_approval", "Waiting Approval"),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="external_sync_events"
    )
    task = models.ForeignKey(
        DerivedTask,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="external_sync_events",
    )
    task_event = models.ForeignKey(
        DerivedTaskEvent,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="external_sync_events",
    )
    provider = models.CharField(max_length=64, default="mock")
    idempotency_key = models.CharField(max_length=255, blank=True, default="")
    status = models.CharField(max_length=32, choices=STATUS_CHOICES, default="pending")
    payload = models.JSONField(default=dict, blank=True)
    error = models.TextField(blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [
            models.Index(fields=["user", "provider", "status", "updated_at"]),
            models.Index(fields=["idempotency_key"]),
        ]


class TaskProviderConfig(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="task_provider_configs"
    )
    provider = models.CharField(max_length=64, default="mock")
    enabled = models.BooleanField(default=False)
    settings = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["user", "provider"],
                name="unique_task_provider_config_per_user",
            )
        ]


class CodexRun(models.Model):
    STATUS_CHOICES = (
        ("queued", "Queued"),
        ("running", "Running"),
        ("waiting_approval", "Waiting Approval"),
        ("approved_waiting_resume", "Approved Waiting Resume"),
        ("denied", "Denied"),
        ("ok", "OK"),
        ("failed", "Failed"),
        ("cancelled", "Cancelled"),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="codex_runs")
    task = models.ForeignKey(
        DerivedTask,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="codex_runs",
    )
    derived_task_event = models.ForeignKey(
        DerivedTaskEvent,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="codex_runs",
    )
    source_message = models.ForeignKey(
        Message,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="codex_runs",
    )
    project = models.ForeignKey(
        TaskProject,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="codex_runs",
    )
    epic = models.ForeignKey(
        TaskEpic,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="codex_runs",
    )
    source_service = models.CharField(max_length=255, blank=True, default="")
    source_channel = models.CharField(max_length=255, blank=True, default="")
    external_chat_id = models.CharField(max_length=255, blank=True, default="")
    status = models.CharField(max_length=32, choices=STATUS_CHOICES, default="queued")
    request_payload = models.JSONField(default=dict, blank=True)
    result_payload = models.JSONField(default=dict, blank=True)
    error = models.TextField(blank=True, default="")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [
            models.Index(fields=["user", "status", "updated_at"]),
            models.Index(
                fields=["user", "source_service", "source_channel", "created_at"]
            ),
        ]


class CodexPermissionRequest(models.Model):
    STATUS_CHOICES = (
        ("pending", "Pending"),
        ("approved", "Approved"),
        ("denied", "Denied"),
        ("expired", "Expired"),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="codex_permission_requests"
    )
    codex_run = models.ForeignKey(
        CodexRun,
        on_delete=models.CASCADE,
        related_name="permission_requests",
    )
    external_sync_event = models.ForeignKey(
        ExternalSyncEvent,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="codex_permission_requests",
    )
    approval_key = models.CharField(max_length=255, unique=True)
    summary = models.TextField(blank=True, default="")
    requested_permissions = models.JSONField(default=dict, blank=True)
    resume_payload = models.JSONField(default=dict, blank=True)
    status = models.CharField(max_length=16, choices=STATUS_CHOICES, default="pending")
    requested_at = models.DateTimeField(auto_now_add=True)
    resolved_at = models.DateTimeField(null=True, blank=True)
    resolved_by_identifier = models.CharField(max_length=255, blank=True, default="")
    resolution_note = models.TextField(blank=True, default="")

    class Meta:
        indexes = [
            models.Index(fields=["user", "status", "requested_at"]),
            models.Index(fields=["approval_key"]),
        ]


class ContactAvailabilitySettings(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name="contact_availability_settings",
    )
    enabled = models.BooleanField(default=True)
    show_in_chat = models.BooleanField(default=True)
    show_in_groups = models.BooleanField(default=True)
    inference_enabled = models.BooleanField(default=True)
    retention_days = models.PositiveIntegerField(default=90)
    fade_threshold_seconds = models.PositiveIntegerField(default=900)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


class ExternalChatLink(models.Model):
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="external_chat_links",
    )
    provider = models.CharField(max_length=64, default="mock")
    person = models.ForeignKey(
        Person,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name="external_chat_links",
    )
    person_identifier = models.ForeignKey(
        PersonIdentifier,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="external_chat_links",
    )
    external_chat_id = models.CharField(max_length=255)
    metadata = models.JSONField(default=dict, blank=True)
    enabled = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [
            models.Index(fields=["user", "provider", "external_chat_id"]),
            models.Index(fields=["user", "provider", "enabled"]),
        ]
        constraints = [
            models.UniqueConstraint(
                fields=["user", "provider", "external_chat_id"],
                name="unique_external_chat_link_per_provider",
            )
        ]


class UserXmppOmemoState(models.Model):
    STATUS_CHOICES = (
        ("pending", "Pending"),
        ("detected", "Detected"),
        ("no_omemo", "No OMEMO"),
        ("error", "Error"),
    )

    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name="xmpp_omemo_state",
    )
    status = models.CharField(max_length=32, choices=STATUS_CHOICES, default="pending")
    latest_client_key = models.CharField(max_length=255, blank=True, default="")
    last_sender_jid = models.CharField(max_length=255, blank=True, default="")
    last_target_jid = models.CharField(max_length=255, blank=True, default="")
    status_reason = models.TextField(blank=True, default="")
    details = models.JSONField(blank=True, default=dict)
    last_seen_at = models.DateTimeField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [
            models.Index(
                fields=["status", "updated_at"], name="core_userxm_status_133ead_idx"
            ),
        ]


class UserXmppOmemoTrustedKey(models.Model):
    KEY_TYPE_CHOICES = (
        ("fingerprint", "Fingerprint"),
        ("client_key", "Client key"),
    )

    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="xmpp_omemo_trusted_keys",
    )
    jid = models.CharField(max_length=255, blank=True, default="")
    key_type = models.CharField(
        max_length=32, choices=KEY_TYPE_CHOICES, default="fingerprint"
    )
    key_id = models.CharField(max_length=255)
    trusted = models.BooleanField(default=False)
    source = models.CharField(max_length=64, blank=True, default="")
    last_seen_at = models.DateTimeField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["user", "jid", "key_type", "key_id"],
                name="unique_user_xmpp_omemo_trusted_key",
            ),
        ]
        indexes = [
            models.Index(
                fields=["user", "trusted", "updated_at"],
                name="core_userxomemo_trusted_idx",
            ),
            models.Index(
                fields=["user", "jid", "updated_at"], name="core_userxomemo_jid_idx"
            ),
        ]


class UserXmppSecuritySettings(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name="xmpp_security_settings",
    )
    require_omemo = models.BooleanField(default=False)
    encrypt_component_messages_with_omemo = models.BooleanField(default=True)
    encrypt_contact_messages_with_omemo = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


class UserAccessibilitySettings(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name="accessibility_settings",
    )
    disable_animations = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


class TaskCompletionPattern(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="task_completion_patterns"
    )
    phrase = models.CharField(max_length=64)
    enabled = models.BooleanField(default=True)
    position = models.PositiveIntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["user", "phrase"],
                name="unique_task_completion_phrase_per_user",
            )
        ]
        indexes = [models.Index(fields=["user", "enabled", "position"])]


# class Perms(models.Model):
#     class Meta:
#         permissions = (
#             ("bypass_hashing", "Can bypass field hashing"),  #
#             ("bypass_blacklist", "Can bypass the blacklist"),  #
#             ("bypass_encryption", "Can bypass field encryption"),  #
#             ("bypass_obfuscation", "Can bypass field obfuscation"),  #
#             ("bypass_delay", "Can bypass data delay"),  #
#             ("bypass_randomisation", "Can bypass data randomisation"),  #
#             ("post_irc", "Can post to IRC"),
#             ("post_discord", "Can post to Discord"),
#             ("query_search", "Can search with query strings"),  #
#             ("use_insights", "Can use the Insights page"),
#             ("index_int", "Can use the internal index"),
#             ("index_meta", "Can use the meta index"),
#             ("restricted_sources", "Can access restricted sources"),
#         )
