"""Add knowledge ontology schema support.

Revision ID: add_knowledge_schema
Revises: quality_contract_pipeline
Create Date: 2026-03-04 14:00:00.000000

Adds:
- node_kind column to concepts table
- concept_relationships table for typed concept-to-concept edges
"""

from __future__ import annotations

from typing import Sequence

import sqlalchemy as sa
from alembic import op

from pycharter.db.migrations.schema_helper import get_schema

revision: str = "add_knowledge_schema"
down_revision: str | None = "quality_contract_pipeline"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    bind = op.get_bind()
    is_sqlite = bind.dialect.name == "sqlite"
    schema_name = get_schema(bind)

    uuid_type = sa.UUID()

    if is_sqlite:
        datetime_default = None
    else:
        datetime_default = sa.text("now()")

    def _fk(table: str) -> str:
        """Build schema-qualified FK reference."""
        return f'{schema_name + "." if schema_name else ""}{table}'

    # Add node_kind column to concepts
    op.add_column(
        "concepts",
        sa.Column("node_kind", sa.String(50), nullable=True),
        schema=schema_name,
    )

    # Create concept_relationships table
    op.create_table(
        "concept_relationships",
        sa.Column("id", uuid_type, nullable=False),
        sa.Column("source_concept_id", uuid_type, nullable=False),
        sa.Column("target_concept_id", uuid_type, nullable=False),
        sa.Column("relationship_type", sa.String(50), nullable=False),
        sa.Column("metadata", sa.JSON(), nullable=True),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=datetime_default,
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            server_default=datetime_default,
        ),
        sa.Column("created_by", sa.String(255), nullable=True),
        sa.PrimaryKeyConstraint("id"),
        sa.ForeignKeyConstraint(
            ["source_concept_id"],
            [f"{_fk('concepts')}.id"],
            ondelete="CASCADE",
        ),
        sa.ForeignKeyConstraint(
            ["target_concept_id"],
            [f"{_fk('concepts')}.id"],
            ondelete="CASCADE",
        ),
        schema=schema_name,
    )
    op.create_index(
        "ix_concept_relationships_source",
        "concept_relationships",
        ["source_concept_id"],
        schema=schema_name,
    )
    op.create_index(
        "ix_concept_relationships_target",
        "concept_relationships",
        ["target_concept_id"],
        schema=schema_name,
    )


def downgrade() -> None:
    bind = op.get_bind()
    schema_name = get_schema(bind)

    op.drop_table("concept_relationships", schema=schema_name)
    op.drop_column("concepts", "node_kind", schema=schema_name)
