import uuid6
from datetime import datetime, timezone
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.exc import IntegrityError
from sqlalchemy import DateTime, String, inspect
from sqlalchemy.dialects.mysql import CHAR
from app.extensions import db

import logging
logger = logging.getLogger(__name__)

def utcnow():
    """
    Returns the current UTC datetime with timezone-aware info.
    
    Returns:
        datetime: Current UTC timestamp.
    """
    return datetime.now(timezone.utc)

class BaseModel(db.Model):
    """
    Abstract base model that serves as the foundation for all models in AKSARA.
    
    Provides standardized fields and behaviors:
    - UUIDv7 Primary Key (Time-ordered, index-friendly).
    - Timestamp fields (created_at, updated_at).
    - Soft delete capability (deleted_at).
    - Audit fields (created_by, updated_by, deleted_by).
    - Optimistic concurrency control via version_id.
    """
    __abstract__ = True

    # ID: UUIDv7 as Primary Key (stored as CHAR(36) for compatibility)
    id: Mapped[str] = mapped_column(CHAR(36), primary_key=True, default=lambda: str(uuid6.uuid7()))

    # Concurrency Control (Optimistic Locking)
    # Automatically incremented by SQLAlchemy on each update.
    version_id: Mapped[int] = mapped_column(default=1, nullable=False)

    __mapper_args__ = {
        "version_id_col": version_id
    }

    # Timestamps
    created_at: Mapped[datetime] = mapped_column(DateTime, default=utcnow, nullable=False)
    updated_at: Mapped[datetime] = mapped_column(DateTime, default=utcnow, onupdate=utcnow, nullable=False)

    # Soft Delete field
    deleted_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)

    # Audit fields (storing User IDs as CHAR(36) strings)
    created_by: Mapped[str | None] = mapped_column(CHAR(36), nullable=True)
    updated_by: Mapped[str | None] = mapped_column(CHAR(36), nullable=True)
    deleted_by: Mapped[str | None] = mapped_column(CHAR(36), nullable=True)

    def save(self, _retries: int = 3, flush_only: bool = False):
        """
        Persists the current instance to the database.
        
        Handles extremely unlikely PK collisions for new records by regenerating 
        UUIDv7 and retrying.

        Args:
            _retries (int): Maximum number of retry attempts on PK collision. Defaults to 3.
            flush_only (bool): If True, issues a session.flush() instead of commit(). 
                               Highly recommended for batch operations to improve performance.
        
        Raises:
            IntegrityError: If a non-PK related constraint is violated or retries are exhausted.
        """
        is_new = inspect(self).transient or inspect(self).pending

        for attempt in range(1, _retries + 1):
            try:
                db.session.add(self)
                if not flush_only:
                    db.session.commit()
                else:
                    db.session.flush()
                return  # Success
            except IntegrityError as e:
                db.session.rollback()
                error_msg = str(e.orig).lower() if e.orig else str(e).lower()
                is_pk_collision = 'primary' in error_msg or f"'{self.id}'" in error_msg

                if is_new and is_pk_collision and attempt < _retries:
                    old_id = self.id
                    self.id = str(uuid6.uuid7())
                    logger.warning(
                        f"{self.__class__.__name__}.save() PK collision "
                        f"(attempt {attempt}/{_retries}): {old_id} → {self.id}"
                    )
                    continue  # Retry with new UUID
                else:
                    raise  # Re-raise if not a PK issue or retries exhausted

    def delete(self, commit: bool = True):
        """
        Hard deletes the instance from the database physically.
        
        Args:
            commit (bool): Whether to commit the transaction. Defaults to True.
        """
        db.session.delete(self)
        if commit:
            db.session.commit()

    def soft_delete(self, user_id: str = None, commit: bool = True):
        """
        Marks the instance as deleted without physical removal.
        Sets deleted_at and deleted_by fields.

        Args:
            user_id (str, optional): The UUID of the user performing the deletion.
            commit (bool): Whether to commit the transaction. Defaults to True.
        """
        self.deleted_at = utcnow()
        if user_id:
            self.deleted_by = user_id
        
        db.session.add(self)
        if commit:
            db.session.commit()
        else:
            db.session.flush()

    @classmethod
    def query_active(cls):
        """
        Returns a base query object filtered to exclude soft-deleted records.
        
        Returns:
            Query: SQLAlchemy query object for active records.
        """
        return cls.query.filter(cls.deleted_at.is_(None))
