from sqlalchemy import create_engine, Column, Integer, String, DateTime, Text, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.sql import func
from datetime import datetime
import os

Base = declarative_base()

class APIKey(Base):
    __tablename__ = 'api_keys'
    
    id = Column(Integer, primary_key=True, index=True)
    key = Column(String(255), unique=True, index=True, nullable=False)
    description = Column(String(255), nullable=True)
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())

class ProjectMapping(Base):
    __tablename__ = 'project_mappings'
    
    id = Column(Integer, primary_key=True, index=True)
    repository_name = Column(String(255), unique=True, index=True, nullable=False)
    default_job = Column(String(255), nullable=False)
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
    
    # 关系
    branch_jobs = relationship("BranchJob", back_populates="project", cascade="all, delete-orphan")
    branch_patterns = relationship("BranchPattern", back_populates="project", cascade="all, delete-orphan")

class BranchJob(Base):
    __tablename__ = 'branch_jobs'
    
    id = Column(Integer, primary_key=True, index=True)
    project_id = Column(Integer, ForeignKey('project_mappings.id'), nullable=False)
    branch_name = Column(String(255), nullable=False)
    job_name = Column(String(255), nullable=False)
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
    
    # 关系
    project = relationship("ProjectMapping", back_populates="branch_jobs")

class BranchPattern(Base):
    __tablename__ = 'branch_patterns'
    
    id = Column(Integer, primary_key=True, index=True)
    project_id = Column(Integer, ForeignKey('project_mappings.id'), nullable=False)
    pattern = Column(String(255), nullable=False)
    job_name = Column(String(255), nullable=False)
    created_at = Column(DateTime, default=func.now())
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
    
    # 关系
    project = relationship("ProjectMapping", back_populates="branch_patterns")

class TriggerLog(Base):
    __tablename__ = 'trigger_logs'
    
    id = Column(Integer, primary_key=True, index=True)
    repository_name = Column(String(255), nullable=False)
    branch_name = Column(String(255), nullable=False)
    commit_sha = Column(String(255), nullable=False)
    job_name = Column(String(255), nullable=False)
    status = Column(String(50), nullable=False)  # success, failed, pending
    error_message = Column(Text, nullable=True)
    created_at = Column(DateTime, default=func.now())

# 数据库配置
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./gitea_webhook_ambassador.db")

# 创建引擎
engine = create_engine(
    DATABASE_URL,
    connect_args={"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {}
)

# 创建会话
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建表
def create_tables():
    Base.metadata.create_all(bind=engine)

# 获取数据库会话
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close() 