from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, ForeignKey, JSON, BigInteger
from sqlalchemy.orm import relationship
from datetime import datetime
from backend.app.core.database import Base

class User(Base):
    __tablename__ = "users"
    
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, index=True, default="admin")
    hashed_password = Column(String(255))
    is_active = Column(Boolean, default=True)

class Camera(Base):
    __tablename__ = "cameras"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100))
    stream_url = Column(String(500))
    status = Column(Integer, default=0) # 0: offline, 1: online
    created_at = Column(DateTime, default=datetime.utcnow)

class ModelConfig(Base):
    __tablename__ = "model_configs"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(50))
    base_url = Column(String(255))
    api_key = Column(String(255))
    model_name = Column(String(100))

class Task(Base):
    __tablename__ = "tasks"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100))
    model_config_id = Column(Integer, ForeignKey("model_configs.id"))
    camera_ids = Column(JSON) # [1, 5, 12]
    rules = Column(JSON) # List of {name, prompt}
    cron_expression = Column(String(50))
    is_running = Column(Boolean, default=False)
    
    model_config = relationship("ModelConfig")

class TaskLog(Base):
    __tablename__ = "task_logs"
    
    id = Column(BigInteger, primary_key=True, index=True)
    task_id = Column(Integer, ForeignKey("tasks.id"))
    camera_id = Column(Integer, ForeignKey("cameras.id"))
    check_time = Column(DateTime, default=datetime.utcnow)
    snapshot_path = Column(String(255))
    
    # New fields
    alarm_name = Column(String(100))
    alarm_content = Column(Text)
    area = Column(String(100))
    is_alarm = Column(Boolean, default=False)
    
    task = relationship("Task")
    camera = relationship("Camera")

class DutyReport(Base):
    __tablename__ = "duty_reports"

    id = Column(Integer, primary_key=True, index=True)
    reporter_name = Column(String(100))
    start_time = Column(DateTime)
    end_time = Column(DateTime)
    status = Column(String(20), default="pending")  # pending, completed, failed
    file_path = Column(String(255), nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow)
