from typing import List, Optional
from pydantic import BaseModel
from sqlalchemy import (
    Column, Integer, String, Text, Boolean, DateTime, JSON
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql import func

Base = declarative_base()


class RedactionRule(BaseModel):
    """Redaction rule configuration"""
    name: str
    description: str
    data_type: str


class Replacement(BaseModel):
    """A single text replacement"""
    original_text: str
    replacement_text: str


class RedactionResult(BaseModel):
    """Result of a redaction operation"""
    original_text: str
    redacted_text: str
    replacements: List[Replacement]
    is_redacted: bool
    processing_time_ms: int
    rule_group_id: Optional[str] = None
    cached: bool = False


# Database Models
class HistoryRecord(Base):
    """Database model for redaction history"""
    __tablename__ = "history"
    
    id = Column(String(50), primary_key=True)
    prompt = Column(Text, nullable=False)
    is_redacted = Column(Boolean, default=False)
    processed_prompt = Column(Text, nullable=True)
    replacements = Column(JSON, nullable=True)
    created_at = Column(DateTime, default=func.now())
    processing_time_ms = Column(Integer, nullable=True)
    rule_group_id = Column(String(50), nullable=True)
    status = Column(String(20), default="pending")
    error_message = Column(Text, nullable=True)


class RuleRecord(Base):
    """Database model for redaction rules"""
    __tablename__ = "rule"
    
    id = Column(String(50), primary_key=True)
    name = Column(Text, nullable=False)
    description = Column(Text, nullable=False)
    data_type = Column(String(50), nullable=False)
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
    is_active = Column(Boolean, default=True)
    is_archived = Column(Boolean, default=False)


class RuleGroup(Base):
    """Database model for rule groups"""
    __tablename__ = "rule_group"
    
    id = Column(String(50), primary_key=True)
    name = Column(Text, nullable=False)
    description = Column(Text, nullable=False)
    rule_ids = Column(JSON, nullable=False)  # List of rule IDs as JSON
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
    is_active = Column(Boolean, default=True)


class PlaceholderMapping(Base):
    """Database model for placeholder-to-original text mappings"""
    __tablename__ = "placeholder_mapping"
    
    id = Column(String(50), primary_key=True)  # data_type + hash
    original_text = Column(Text, nullable=False)  # Original sensitive text
    created_at = Column(DateTime, default=func.now())
    usage_count = Column(Integer, default=1) 