"""
Database models for groknroll
"""

from datetime import datetime

from sqlalchemy import JSON, Column, DateTime, Float, ForeignKey, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()


class Project(Base):
    """Project metadata"""

    __tablename__ = "projects"

    id = Column(Integer, primary_key=True)
    path = Column(String, unique=True, nullable=False, index=True)
    name = Column(String, nullable=False)
    language = Column(String)  # Primary language
    total_files = Column(Integer, default=0)
    total_lines = Column(Integer, default=0)
    last_indexed = Column(DateTime)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # Relationships
    files = relationship("FileIndex", back_populates="project", cascade="all, delete-orphan")
    executions = relationship("Execution", back_populates="project", cascade="all, delete-orphan")
    sessions = relationship("Session", back_populates="project", cascade="all, delete-orphan")
    analyses = relationship("Analysis", back_populates="project", cascade="all, delete-orphan")


class FileIndex(Base):
    """Indexed file metadata"""

    __tablename__ = "file_index"

    id = Column(Integer, primary_key=True)
    project_id = Column(Integer, ForeignKey("projects.id"), nullable=False, index=True)
    path = Column(String, nullable=False, index=True)
    relative_path = Column(String, nullable=False)
    language = Column(String)
    size_bytes = Column(Integer)
    lines_of_code = Column(Integer)
    complexity = Column(Float)  # Cyclomatic complexity
    last_modified = Column(DateTime)
    ast_data = Column(JSON)  # Parsed AST metadata
    imports = Column(JSON)  # List of imports
    exports = Column(JSON)  # List of exports
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # Relationships
    project = relationship("Project", back_populates="files")


class Execution(Base):
    """RLM execution history"""

    __tablename__ = "executions"

    id = Column(Integer, primary_key=True)
    project_id = Column(Integer, ForeignKey("projects.id"), index=True)
    session_id = Column(Integer, ForeignKey("sessions.id"), index=True)

    # Request
    task = Column(Text, nullable=False)
    context = Column(JSON)
    model = Column(String)

    # Response
    response = Column(Text)
    trace_log = Column(Text)

    # Metrics
    total_cost = Column(Float)
    total_time = Column(Float)
    iterations = Column(Integer)
    status = Column(String)  # success, failed, timeout
    error_message = Column(Text)

    # Timestamps
    started_at = Column(DateTime, default=datetime.utcnow, index=True)
    completed_at = Column(DateTime)
    created_at = Column(DateTime, default=datetime.utcnow)

    # Relationships
    project = relationship("Project", back_populates="executions")
    session = relationship("Session", back_populates="executions")


class Session(Base):
    """Interactive session history"""

    __tablename__ = "sessions"

    id = Column(Integer, primary_key=True)
    project_id = Column(Integer, ForeignKey("projects.id"), index=True)

    session_type = Column(String)  # chat, repl, dashboard
    started_at = Column(DateTime, default=datetime.utcnow, index=True)
    ended_at = Column(DateTime)
    message_count = Column(Integer, default=0)
    total_cost = Column(Float, default=0.0)

    # Relationships
    project = relationship("Project", back_populates="sessions")
    executions = relationship("Execution", back_populates="session", cascade="all, delete-orphan")


class Analysis(Base):
    """Code analysis results"""

    __tablename__ = "analyses"

    id = Column(Integer, primary_key=True)
    project_id = Column(Integer, ForeignKey("projects.id"), index=True)

    analysis_type = Column(String, nullable=False)  # security, complexity, review, etc
    target_path = Column(String)  # File or directory analyzed
    results = Column(JSON)  # Analysis results
    recommendations = Column(JSON)  # Recommendations
    issues = Column(JSON)  # Issues found
    metrics = Column(JSON)  # Metrics

    execution_time = Column(Float)
    created_at = Column(DateTime, default=datetime.utcnow, index=True)

    # Relationships
    project = relationship("Project", back_populates="analyses")
