from app.extensions import db, login_manager
from flask_login import UserMixin
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy import String, Boolean, ForeignKey, Table, Column, Text
from sqlalchemy.dialects.mysql import CHAR
from .base import BaseModel
from werkzeug.security import generate_password_hash, check_password_hash

# Association Table for Role <-> Permission
# Links roles to their granular permissions in a many-to-many relationship.
role_permissions = db.Table(
    'role_permissions',
    db.Column('role_id', CHAR(36), db.ForeignKey('role.id'), primary_key=True),
    db.Column('permission_id', CHAR(36), db.ForeignKey('permission.id'), primary_key=True)
)

class Permission(BaseModel):
    """
    Represents a granular permission in the system.
    
    Permissions are defined by slugs (e.g., 'crm.leads.create') and assigned to roles.
    """
    __tablename__ = 'permission'
    
    slug: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
    description: Mapped[str | None] = mapped_column(String(255), nullable=True)

    def __repr__(self):
        return f"<Permission {self.slug}>"

class Role(BaseModel):
    """
    Represents a user role within the organization.
    
    Roles group multiple permissions together (e.g., 'Admin', 'Sales Manager')
    to simplify user access management.
    """
    __tablename__ = 'role'
    
    name: Mapped[str] = mapped_column(String(50), unique=True, nullable=False)
    
    # Relationships
    permissions = relationship('Permission', secondary=role_permissions, backref='roles')

    def __repr__(self):
        return f"<Role {self.name}>"

class User(BaseModel, UserMixin):
    """
    Represents a system user account for authentication and authorization.
    
    Users are linked to a single role and optionally to an employee profile.
    """
    __tablename__ = 'user'
    
    username: Mapped[str | None] = mapped_column(String(64), unique=True, nullable=True)
    email: Mapped[str] = mapped_column(String(120), unique=True, nullable=False)
    password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True)

    # Role Link
    role_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('role.id'), nullable=True)
    role = relationship('Role', backref='users')

    # Employee Link
    employee = relationship('Employee', back_populates='user', uselist=False)

    def set_password(self, password: str):
        """
        Hashes and sets the user's password.
        
        Args:
            password (str): Plaintext password to hash.
        """
        self.password_hash = generate_password_hash(password)

    def check_password(self, password: str) -> bool:
        """
        Verifies the user's password against the stored hash.
        
        Args:
            password (str): Plaintext password to verify.
            
        Returns:
            bool: True if password is correct, False otherwise.
        """
        return check_password_hash(self.password_hash, password)

    @property
    def display_name(self) -> str:
        """
        Retrieves the most appropriate display name for the user.
        
        Prioritizes the linked employee's full_name, falls back to username, 
        and then email if others are missing.
        
        Returns:
            str: The user's display name.
        """
        if self.employee and self.employee.full_name:
            return self.employee.full_name
        return self.username or self.email
    
    @property
    def permissions(self) -> set[str]:
        """
        Retrieves the set of permission slugs associated with the user's role.
        
        Results are cached at the request level on the user object to avoid 
        redundant database queries (N+1 problem) in decorators and templates.
        
        Returns:
            set[str]: A set of permission slug strings.
        """
        if not hasattr(self, '_perm_cache'):
            if not self.role:
                self._perm_cache = set()
            else:
                self._perm_cache = {p.slug for p in self.role.permissions}
        return self._perm_cache

    def has_permission(self, perm_slug: str) -> bool:
        """
        Checks if the user has a specific permission.
        
        Includes a bypass for users with 'Admin' or 'SuperAdmin' roles.
        
        Args:
            perm_slug (str): The permission slug to check.
            
        Returns:
            bool: True if the user is authorized, False otherwise.
        """
        if self.is_admin():
            return True
        return perm_slug in self.permissions
    
    def can(self, permission_key: str) -> bool:
        """
        Check if user has specific permission. Alias for has_permission.
        
        Args:
            permission_key (str): The permission slug.
            
        Returns:
            bool: Authorization result.
        """
        if not self.is_authenticated:
            return False
        return self.has_permission(permission_key)

    def can_all(self, *permission_keys: str) -> bool:
        """
        Check if the user has ALL of the specified permissions.
        
        Args:
            *permission_keys: Variable list of permission slugs.
            
        Returns:
            bool: True if all permissions are granted.
        """
        if not self.is_authenticated:
            return False
        if self.is_admin():
            return True
        return all(self.has_permission(perm) for perm in permission_keys)

    def can_any(self, *permission_keys: str) -> bool:
        """
        Check if the user has AT LEAST ONE of the specified permissions.
        
        Args:
            *permission_keys: Variable list of permission slugs.
            
        Returns:
            bool: True if any one permission is granted.
        """
        if not self.is_authenticated:
            return False
        if self.is_admin():
            return True
        return any(self.has_permission(perm) for perm in permission_keys)

    def is_admin(self) -> bool:
        """
        Checks if the user has an administrative role.
        
        Returns:
            bool: True if user is an Admin or SuperAdmin.
        """
        return self.role and self.role.name in ['SuperAdmin', 'Admin']

    @property
    def role_level(self) -> int:
        """
        Returns an integer representing the hierarchy level of the user's role.
        Useful for UI ordering or secondary authorization logic.
        
        Returns:
            int: Level value (higher is more privileged).
        """
        if not self.role:
            return 0
        hierarchy = {
            'Admin': 100,
            'General Manager': 90,
            'HR Manager': 80,
            'Sales Manager': 80,
            'Support Manager': 80,
            'Project Manager': 80,
            'Finance': 70,
            'Sales Agent': 50,
            'Support Agent': 50,
            'User': 10
        }
        return hierarchy.get(self.role.name, 0)

    @property
    def assigned_data(self) -> dict:
        """
        Check the availability of assignment data (Lead, Ticket, Project) for this user.
        The result is cached at the request level to avoid N+1 queries in templates.
        """
        # Return cache if already computed in this request
        if hasattr(self, '_assigned_data_cache'):
            return self._assigned_data_cache

        # Default state
        cache = {
            'has_leads': False,
            'has_tickets': False,
            'has_projects': False,
            'has_tasks': False
        }

        # Avoid execution if user is not logged in
        if not self.is_authenticated:
            self._assigned_data_cache = cache
            return cache

        # Local import to avoid Circular Import Errors
        from sqlalchemy import select
        from app.modules.crm.models import Lead, Ticket
        from app.modules.erp.models.core import Project
        from app.core.models.task import Task

        # Execute super fast EXISTS query (scalar & limit 1)
        # Assumption: Lead and Ticket use .assignees relationship, Project uses .members
        
        # 1. Check Leads (Relations M:M with User via .assignees)
        stmt_lead = select(Lead.id).where(Lead.assignees.any(User.id == self.id)).limit(1)
        cache['has_leads'] = db.session.scalar(stmt_lead) is not None

        # 2. Check Tickets (Relations M:M with User via .assignees)
        stmt_ticket = select(Ticket.id).where(Ticket.assignees.any(User.id == self.id)).limit(1)
        cache['has_tickets'] = db.session.scalar(stmt_ticket) is not None

        # 3. Check Projects (As project manager relationship)
        stmt_project = select(Project.id).where(Project.pm_id == self.id).limit(1)
        cache['has_projects'] = db.session.scalar(stmt_project) is not None

        # 4. Check Tasks (Relations M:M with User via .assignees)
        stmt_task = select(Task.id).where(Task.assignees.any(User.id == self.id)).limit(1)
        cache['has_tasks'] = db.session.scalar(stmt_task) is not None

        # Save to cache
        self._assigned_data_cache = cache
        return cache

    def __repr__(self):
        return f"<User {self.email}>"

@login_manager.user_loader
def load_user(user_id: str):
    """
    Flask-Login user loader callback.
    Retrieves a user object from the database by ID.
    
    Args:
        user_id (str): UUID string of the user.
        
    Returns:
        User: Matching User object or None.
    """
    return db.session.get(User, user_id)

class ActivityLog(BaseModel):
    """
    Logs critical system-wide events and administrative actions.
    
    Focuses on high-level actions like force deletions or configuration changes
    rather than granular entity property changes (which are handled by AuditLog).
    """
    __tablename__ = 'activity_log'
    
    user_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('user.id'), nullable=True)
    action: Mapped[str] = mapped_column(String(100), nullable=False) # e.g. FORCE_DELETE_EMPLOYEE
    details: Mapped[str | None] = mapped_column(Text, nullable=True) # E.g. JSON or text reason
    ip_address: Mapped[str | None] = mapped_column(String(45), nullable=True)

    # Relationships
    user = relationship('User')

    def __repr__(self):
        return f"<ActivityLog {self.action} by {self.user_id}>"
