from datetime import datetime
from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, JSON, Float, Boolean
from sqlalchemy.orm import relationship

from app.core.database import Base


class Category(Base):
    __tablename__ = "category"

    id = Column(Integer, primary_key=True, index=True)
    parent_id = Column(Integer, ForeignKey("category.id"), nullable=True)
    level = Column(Integer, default=1)  # 1, 2, 3
    code = Column(String(50), unique=True, nullable=False)
    name = Column(String(100), nullable=False)
    description = Column(Text)
    sort_order = Column(Integer, default=0)
    created_at = Column(DateTime, default=datetime.utcnow)

    parent = relationship("Category", remote_side=[id], backref="children")


class DataLevel(Base):
    __tablename__ = "data_level"

    id = Column(Integer, primary_key=True, index=True)
    code = Column(String(20), unique=True, nullable=False)  # L1, L2, L3, L4, L5
    name = Column(String(50), nullable=False)
    description = Column(Text)
    color = Column(String(20), default="#999999")
    control_requirements = Column(JSON)
    sort_order = Column(Integer, default=0)


class RecognitionRule(Base):
    __tablename__ = "recognition_rule"

    id = Column(Integer, primary_key=True, index=True)
    template_id = Column(Integer, ForeignKey("classification_template.id"), nullable=False)
    category_id = Column(Integer, ForeignKey("category.id"), nullable=True)
    level_id = Column(Integer, ForeignKey("data_level.id"), nullable=True)
    rule_type = Column(String(20), nullable=False)  # regex, keyword, enum, ml
    rule_name = Column(String(100))
    rule_content = Column(Text, nullable=False)  # regex pattern / keyword list / enum values
    target_field = Column(String(20), default="column_name")  # column_name, comment, sample_data
    priority = Column(Integer, default=100)
    hit_count = Column(Integer, default=0)
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)

    template = relationship("ClassificationTemplate", back_populates="rules")
    category = relationship("Category")
    level = relationship("DataLevel")


class ClassificationTemplate(Base):
    __tablename__ = "classification_template"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    industry_type = Column(String(50), default="insurance_property")
    version = Column(String(20), default="1.0")
    description = Column(Text)
    is_builtin = Column(Boolean, default=False)
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)

    rules = relationship("RecognitionRule", back_populates="template", cascade="all, delete-orphan")
