"""initial schema

Revision ID: 52db06c8cbdd
Revises: 
Create Date: 2026-03-15 09:07:30.174892+00:00

"""
from __future__ import annotations

from typing import Sequence, Union

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

revision: str = '52db06c8cbdd'
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:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('agents',
    sa.Column('agent_id', sa.UUID(), nullable=False),
    sa.Column('display_name', sa.Text(), nullable=True),
    sa.Column('capabilities', postgresql.ARRAY(sa.String()), server_default='{}', nullable=False),
    sa.Column('metadata', postgresql.JSONB(astext_type=sa.Text()), server_default='{}', nullable=False),
    sa.Column('trust_level', sa.Float(), server_default='0.5000', nullable=False),
    sa.Column('auth_source', sa.String(length=20), server_default='agentauth', nullable=False),
    sa.Column('public_key', postgresql.BYTEA(), nullable=True),
    sa.Column('agentauth_linked', sa.Boolean(), server_default='false', nullable=False),
    sa.Column('registered_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
    sa.Column('status', sa.String(length=20), server_default='active', nullable=False),
    sa.PrimaryKeyConstraint('agent_id')
    )
    op.create_index('idx_agents_auth_source', 'agents', ['auth_source'], unique=False)
    op.create_index('idx_agents_capabilities', 'agents', ['capabilities'], unique=False, postgresql_using='gin')
    op.create_index('idx_agents_public_key', 'agents', ['public_key'], unique=False, postgresql_where='public_key IS NOT NULL')
    op.create_table('alert_subscriptions',
    sa.Column('subscription_id', sa.UUID(), nullable=False),
    sa.Column('subscriber_id', sa.UUID(), nullable=False),
    sa.Column('watched_agent_id', sa.UUID(), nullable=False),
    sa.Column('callback_tool', sa.String(length=200), nullable=False),
    sa.Column('threshold_delta', sa.Numeric(precision=5, scale=4), server_default='0.0500', nullable=False),
    sa.Column('active', sa.Boolean(), server_default='true', nullable=False),
    sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
    sa.ForeignKeyConstraint(['subscriber_id'], ['agents.agent_id'], ),
    sa.ForeignKeyConstraint(['watched_agent_id'], ['agents.agent_id'], ),
    sa.PrimaryKeyConstraint('subscription_id'),
    sa.UniqueConstraint('subscriber_id', 'watched_agent_id', name='uq_subscription')
    )
    op.create_table('attestations',
    sa.Column('attestation_id', sa.UUID(), nullable=False),
    sa.Column('subject_id', sa.UUID(), nullable=False),
    sa.Column('score_snapshot', postgresql.JSONB(astext_type=sa.Text()), nullable=False),
    sa.Column('valid_from', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
    sa.Column('valid_until', postgresql.TIMESTAMP(timezone=True), nullable=False),
    sa.Column('jwt_token', sa.Text(), nullable=False),
    sa.Column('revoked', sa.Boolean(), server_default='false', nullable=False),
    sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
    sa.ForeignKeyConstraint(['subject_id'], ['agents.agent_id'], ),
    sa.PrimaryKeyConstraint('attestation_id')
    )
    op.create_index('idx_attestations_subject', 'attestations', ['subject_id'], unique=False, postgresql_where='NOT revoked')
    op.create_table('interactions',
    sa.Column('interaction_id', sa.UUID(), nullable=False),
    sa.Column('initiator_id', sa.UUID(), nullable=False),
    sa.Column('counterparty_id', sa.UUID(), nullable=False),
    sa.Column('interaction_type', sa.String(length=50), nullable=False),
    sa.Column('outcome', sa.String(length=20), nullable=False),
    sa.Column('context', postgresql.JSONB(astext_type=sa.Text()), server_default='{}', nullable=False),
    sa.Column('evidence_hash', sa.Text(), nullable=True),
    sa.Column('reported_by', sa.UUID(), nullable=False),
    sa.Column('mutually_confirmed', sa.Boolean(), server_default='false', nullable=False),
    sa.Column('reported_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
    sa.CheckConstraint('initiator_id != counterparty_id', name='no_self_report'),
    sa.ForeignKeyConstraint(['counterparty_id'], ['agents.agent_id'], ),
    sa.ForeignKeyConstraint(['initiator_id'], ['agents.agent_id'], ),
    sa.ForeignKeyConstraint(['reported_by'], ['agents.agent_id'], ),
    sa.PrimaryKeyConstraint('interaction_id')
    )
    op.create_index('idx_interactions_counterparty', 'interactions', ['counterparty_id', 'reported_at'], unique=False)
    op.create_index('idx_interactions_initiator', 'interactions', ['initiator_id', 'reported_at'], unique=False)
    # TimescaleDB requires the partitioning column in the primary key.
    # Drop the single-column PK, then convert to hypertable, then add composite PK.
    op.execute("ALTER TABLE interactions DROP CONSTRAINT interactions_pkey")
    op.execute("SELECT create_hypertable('interactions', 'reported_at', if_not_exists => TRUE)")
    op.execute("ALTER TABLE interactions ADD CONSTRAINT interactions_pkey PRIMARY KEY (interaction_id, reported_at)")
    op.create_table('trust_scores',
    sa.Column('agent_id', sa.UUID(), nullable=False),
    sa.Column('score_type', sa.String(length=50), nullable=False),
    sa.Column('score', sa.Numeric(precision=5, scale=4), nullable=False),
    sa.Column('confidence', sa.Numeric(precision=5, scale=4), nullable=False),
    sa.Column('interaction_count', sa.Integer(), nullable=False),
    sa.Column('factor_breakdown', postgresql.JSONB(astext_type=sa.Text()), server_default='{}', nullable=False),
    sa.Column('computed_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
    sa.ForeignKeyConstraint(['agent_id'], ['agents.agent_id'], ),
    sa.PrimaryKeyConstraint('agent_id', 'score_type')
    )
    op.create_table('disputes',
    sa.Column('dispute_id', sa.UUID(), nullable=False),
    sa.Column('interaction_id', sa.UUID(), nullable=False),
    sa.Column('filed_by', sa.UUID(), nullable=False),
    sa.Column('filed_against', sa.UUID(), nullable=False),
    sa.Column('reason', sa.Text(), nullable=False),
    sa.Column('evidence', postgresql.JSONB(astext_type=sa.Text()), server_default='{}', nullable=False),
    sa.Column('status', sa.String(length=20), server_default='open', nullable=False),
    sa.Column('resolution', sa.String(length=20), nullable=True),
    sa.Column('resolution_note', sa.Text(), nullable=True),
    sa.Column('resolved_by', sa.UUID(), nullable=True),
    sa.Column('resolved_at', postgresql.TIMESTAMP(timezone=True), nullable=True),
    sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
    sa.ForeignKeyConstraint(['filed_against'], ['agents.agent_id'], ),
    sa.ForeignKeyConstraint(['filed_by'], ['agents.agent_id'], ),
    # Note: no FK to interactions — TimescaleDB hypertables don't support inbound FKs.
    # Application logic enforces the interaction_id reference.
    sa.ForeignKeyConstraint(['resolved_by'], ['agents.agent_id'], ),
    sa.PrimaryKeyConstraint('dispute_id')
    )
    op.create_index('idx_disputes_status', 'disputes', ['status'], unique=False, postgresql_where="status = 'open'")
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index('idx_disputes_status', table_name='disputes', postgresql_where="status = 'open'")
    op.drop_table('disputes')
    op.drop_table('trust_scores')
    op.drop_index('idx_interactions_initiator', table_name='interactions')
    op.drop_index('idx_interactions_counterparty', table_name='interactions')
    op.drop_table('interactions')
    op.drop_index('idx_attestations_subject', table_name='attestations', postgresql_where='NOT revoked')
    op.drop_table('attestations')
    op.drop_table('alert_subscriptions')
    op.drop_index('idx_agents_public_key', table_name='agents', postgresql_where='public_key IS NOT NULL')
    op.drop_index('idx_agents_capabilities', table_name='agents', postgresql_using='gin')
    op.drop_index('idx_agents_auth_source', table_name='agents')
    op.drop_table('agents')
    # ### end Alembic commands ###
