"""Initial schema for AI Insights Service

Revision ID: 001
Revises:
Create Date: 2025-11-02 14:30:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID, JSONB

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


def upgrade() -> None:
    # Create ai_insights table
    op.create_table(
        'ai_insights',
        sa.Column('id', UUID(as_uuid=True), primary_key=True),
        sa.Column('tenant_id', UUID(as_uuid=True), nullable=False),
        sa.Column('type', sa.String(50), nullable=False),
        sa.Column('priority', sa.String(20), nullable=False),
        sa.Column('category', sa.String(50), nullable=False),
        sa.Column('title', sa.String(255), nullable=False),
        sa.Column('description', sa.Text, nullable=False),
        sa.Column('impact_type', sa.String(50)),
        sa.Column('impact_value', sa.DECIMAL(10, 2)),
        sa.Column('impact_unit', sa.String(20)),
        sa.Column('confidence', sa.Integer, nullable=False),
        sa.Column('metrics_json', JSONB),
        sa.Column('actionable', sa.Boolean, nullable=False, server_default='true'),
        sa.Column('recommendation_actions', JSONB),
        sa.Column('status', sa.String(20), nullable=False, server_default='new'),
        sa.Column('source_service', sa.String(50)),
        sa.Column('source_data_id', sa.String(100)),
        sa.Column('created_at', sa.TIMESTAMP(timezone=True), server_default=sa.func.now(), nullable=False),
        sa.Column('updated_at', sa.TIMESTAMP(timezone=True), server_default=sa.func.now(), onupdate=sa.func.now(), nullable=False),
        sa.Column('applied_at', sa.TIMESTAMP(timezone=True)),
        sa.Column('expired_at', sa.TIMESTAMP(timezone=True)),
        sa.CheckConstraint('confidence >= 0 AND confidence <= 100', name='check_confidence_range')
    )

    # Create indexes for ai_insights
    op.create_index('idx_tenant_id', 'ai_insights', ['tenant_id'])
    op.create_index('idx_type', 'ai_insights', ['type'])
    op.create_index('idx_priority', 'ai_insights', ['priority'])
    op.create_index('idx_category', 'ai_insights', ['category'])
    op.create_index('idx_confidence', 'ai_insights', ['confidence'])
    op.create_index('idx_status', 'ai_insights', ['status'])
    op.create_index('idx_actionable', 'ai_insights', ['actionable'])
    op.create_index('idx_created_at', 'ai_insights', ['created_at'])
    op.create_index('idx_tenant_status_category', 'ai_insights', ['tenant_id', 'status', 'category'])
    op.create_index('idx_tenant_created_confidence', 'ai_insights', ['tenant_id', 'created_at', 'confidence'])
    op.create_index('idx_actionable_status', 'ai_insights', ['actionable', 'status'])

    # Create insight_feedback table
    op.create_table(
        'insight_feedback',
        sa.Column('id', UUID(as_uuid=True), primary_key=True),
        sa.Column('insight_id', UUID(as_uuid=True), nullable=False),
        sa.Column('action_taken', sa.String(100)),
        sa.Column('result_data', JSONB),
        sa.Column('success', sa.Boolean, nullable=False),
        sa.Column('error_message', sa.Text),
        sa.Column('expected_impact_value', sa.DECIMAL(10, 2)),
        sa.Column('actual_impact_value', sa.DECIMAL(10, 2)),
        sa.Column('variance_percentage', sa.DECIMAL(5, 2)),
        sa.Column('applied_by', sa.String(100)),
        sa.Column('created_at', sa.TIMESTAMP(timezone=True), server_default=sa.func.now(), nullable=False),
        sa.ForeignKeyConstraint(['insight_id'], ['ai_insights.id'], ondelete='CASCADE')
    )

    # Create indexes for insight_feedback
    op.create_index('idx_feedback_insight_id', 'insight_feedback', ['insight_id'])
    op.create_index('idx_feedback_success', 'insight_feedback', ['success'])
    op.create_index('idx_feedback_created_at', 'insight_feedback', ['created_at'])
    op.create_index('idx_insight_success', 'insight_feedback', ['insight_id', 'success'])
    op.create_index('idx_created_success', 'insight_feedback', ['created_at', 'success'])

    # Create insight_correlations table
    op.create_table(
        'insight_correlations',
        sa.Column('id', UUID(as_uuid=True), primary_key=True),
        sa.Column('parent_insight_id', UUID(as_uuid=True), nullable=False),
        sa.Column('child_insight_id', UUID(as_uuid=True), nullable=False),
        sa.Column('correlation_type', sa.String(50), nullable=False),
        sa.Column('correlation_strength', sa.DECIMAL(3, 2), nullable=False),
        sa.Column('combined_confidence', sa.Integer),
        sa.Column('created_at', sa.TIMESTAMP(timezone=True), server_default=sa.func.now(), nullable=False),
        sa.ForeignKeyConstraint(['parent_insight_id'], ['ai_insights.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['child_insight_id'], ['ai_insights.id'], ondelete='CASCADE')
    )

    # Create indexes for insight_correlations
    op.create_index('idx_corr_parent', 'insight_correlations', ['parent_insight_id'])
    op.create_index('idx_corr_child', 'insight_correlations', ['child_insight_id'])
    op.create_index('idx_corr_type', 'insight_correlations', ['correlation_type'])
    op.create_index('idx_corr_created_at', 'insight_correlations', ['created_at'])
    op.create_index('idx_parent_child', 'insight_correlations', ['parent_insight_id', 'child_insight_id'])


def downgrade() -> None:
    op.drop_table('insight_correlations')
    op.drop_table('insight_feedback')
    op.drop_table('ai_insights')
