"""SQLAlchemy ORM models for evolution persistence (SQLite-backed)."""

import uuid
from datetime import datetime, timezone

from sqlalchemy import Column, DateTime, Float, Integer, String, Text, UniqueConstraint, create_engine
from sqlalchemy.orm import declarative_base, sessionmaker

Base = declarative_base()


class EvolutionEventModel(Base):
    """进化事件 ORM 模型"""

    __tablename__ = "evolution_events"

    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    agent_name = Column(String, index=True)
    event_type = Column(String)  # "reflection", "optimization", "ab_test", "apply", "rollback"
    trace_id = Column(String, nullable=True)
    reflection_id = Column(String, nullable=True)
    proposal_id = Column(String, nullable=True)
    change_type = Column(String, nullable=True)
    before = Column(Text, nullable=True)  # JSON string
    after = Column(Text, nullable=True)  # JSON string
    metrics = Column(Text, nullable=True)  # JSON string
    status = Column(String, default="active")  # "active", "rolled_back"
    created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))


class SkillVersionModel(Base):
    """技能版本 ORM 模型"""

    __tablename__ = "skill_versions"
    __table_args__ = (UniqueConstraint('skill_name', 'version'),)

    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    skill_name = Column(String, index=True)
    version = Column(String)
    content = Column(Text)  # JSON string of skill config
    parent_version = Column(String, nullable=True)
    created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))


class ABTestResultModel(Base):
    """A/B 测试结果 ORM 模型"""

    __tablename__ = "ab_test_results"

    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    test_id = Column(String, index=True)
    variant = Column(String)  # "control" or "experiment"
    score = Column(Float)
    sample_count = Column(Integer, default=0)
    created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
