"""add_script_builder_sessions_table

Revision ID: 062
Revises: f0aad74ea51b
Create Date: 2026-03-21 20:54:41.621748

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision: str = '062'
down_revision: Union[str, None] = 'f0aad74ea51b'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.create_table('script_builder_sessions',
        sa.Column('id', sa.UUID(), nullable=False),
        sa.Column('user_id', sa.UUID(), nullable=False),
        sa.Column('team_id', sa.UUID(), nullable=True),
        sa.Column('language', sa.String(length=30), nullable=False, comment='Script language: powershell, bash, python'),
        sa.Column('title', sa.String(length=200), nullable=True, comment='Auto-generated from first AI response'),
        sa.Column('messages', postgresql.JSONB(astext_type=sa.Text()), nullable=False, comment='Array of {role, content, script?, script_filename?, timestamp}'),
        sa.Column('latest_script', sa.Text(), nullable=True, comment='Most recent generated script for quick access'),
        sa.Column('latest_script_filename', sa.String(length=200), nullable=True, comment='Filename of the latest generated script'),
        sa.Column('message_count', sa.Integer(), nullable=False),
        sa.Column('ai_session_id', sa.UUID(), nullable=True, comment='Link to FlowPilot session if launched from there'),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
        sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
        sa.ForeignKeyConstraint(['ai_session_id'], ['ai_sessions.id'], ondelete='SET NULL'),
        sa.ForeignKeyConstraint(['team_id'], ['teams.id'], ondelete='SET NULL'),
        sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_script_builder_sessions_user_id'), 'script_builder_sessions', ['user_id'], unique=False)


def downgrade() -> None:
    op.drop_index(op.f('ix_script_builder_sessions_user_id'), table_name='script_builder_sessions')
    op.drop_table('script_builder_sessions')
