"""Add wiki tables for ontology, knowledge graph, and governance

Revision ID: add_wiki_tables
Revises: add_metadata_payload
Create Date: 2026-02-26 12:00:00.000000

Adds 8 tables for the pycharter.wiki subpackage:
- concepts: Concept taxonomy hierarchy (self-referential tree)
- fields: Field-level ontology annotations per contract
- field_concepts: M2M join between fields and concepts
- field_relationships: Typed relationships between fields
- contract_versions: Git-like version history for ontology content
- branches: Named branches for version control
- proposals: Change proposals (like pull requests)
- reviews: Review decisions on proposals
"""

from __future__ import annotations

from typing import Sequence

import sqlalchemy as sa
from alembic import op

revision: str = "add_wiki_tables"
down_revision: str | None = "add_metadata_payload"
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 = None if is_sqlite else "pycharter"

    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}'

    # --- concepts ---
    op.create_table(
        "concepts",
        sa.Column("id", uuid_type, nullable=False),
        sa.Column("name", sa.String(255), nullable=False),
        sa.Column("description", sa.Text(), nullable=True),
        sa.Column("parent_id", uuid_type, nullable=True),
        sa.Column("tier", sa.String(50), nullable=False, server_default="free"),
        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.Column("updated_by", sa.String(255), nullable=True),
        sa.PrimaryKeyConstraint("id"),
        sa.ForeignKeyConstraint(
            ["parent_id"],
            [f"{_fk('concepts')}.id"],
            ondelete="SET NULL",
        ),
        sa.UniqueConstraint("name", name="uq_concepts_name"),
        schema=schema_name,
    )

    # --- fields ---
    op.create_table(
        "fields",
        sa.Column("id", uuid_type, nullable=False),
        sa.Column("contract_id", sa.String(255), nullable=False),
        sa.Column("name", sa.String(255), nullable=False),
        sa.Column("data_type", sa.String(100), nullable=True),
        sa.Column("business_definition", sa.Text(), 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.Column("updated_by", sa.String(255), nullable=True),
        sa.PrimaryKeyConstraint("id"),
        schema=schema_name,
    )
    op.create_index(
        "ix_fields_contract_id",
        "fields",
        ["contract_id"],
        schema=schema_name,
    )

    # --- field_concepts (M2M join) ---
    op.create_table(
        "field_concepts",
        sa.Column("id", uuid_type, nullable=False),
        sa.Column("field_id", uuid_type, nullable=False),
        sa.Column("concept_id", uuid_type, nullable=False),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=datetime_default,
        ),
        sa.PrimaryKeyConstraint("id"),
        sa.ForeignKeyConstraint(
            ["field_id"],
            [f"{_fk('fields')}.id"],
            ondelete="CASCADE",
        ),
        sa.ForeignKeyConstraint(
            ["concept_id"],
            [f"{_fk('concepts')}.id"],
            ondelete="CASCADE",
        ),
        sa.UniqueConstraint("field_id", "concept_id", name="uq_field_concept"),
        schema=schema_name,
    )

    # --- field_relationships ---
    op.create_table(
        "field_relationships",
        sa.Column("id", uuid_type, nullable=False),
        sa.Column("source_field_id", uuid_type, nullable=False),
        sa.Column("target_field_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.Column("updated_by", sa.String(255), nullable=True),
        sa.PrimaryKeyConstraint("id"),
        sa.ForeignKeyConstraint(
            ["source_field_id"],
            [f"{_fk('fields')}.id"],
            ondelete="CASCADE",
        ),
        sa.ForeignKeyConstraint(
            ["target_field_id"],
            [f"{_fk('fields')}.id"],
            ondelete="CASCADE",
        ),
        schema=schema_name,
    )

    # --- branches (must be before contract_versions due to FK) ---
    op.create_table(
        "branches",
        sa.Column("id", uuid_type, nullable=False),
        sa.Column("contract_id", sa.String(255), nullable=False),
        sa.Column("name", sa.String(255), nullable=False),
        sa.Column("base_version_id", uuid_type, nullable=True),
        sa.Column("status", sa.String(50), nullable=False, server_default="open"),
        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.Column("updated_by", sa.String(255), nullable=True),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("contract_id", "name", name="uq_branches_contract_name"),
        schema=schema_name,
    )
    op.create_index(
        "ix_branches_contract_id",
        "branches",
        ["contract_id"],
        schema=schema_name,
    )

    # --- contract_versions ---
    op.create_table(
        "contract_versions",
        sa.Column("id", uuid_type, nullable=False),
        sa.Column("contract_id", sa.String(255), nullable=False),
        sa.Column("parent_id", uuid_type, nullable=True),
        sa.Column("branch_id", uuid_type, nullable=True),
        sa.Column("content", sa.JSON(), nullable=False),
        sa.Column("message", sa.Text(), nullable=False),
        sa.Column("author", sa.String(255), nullable=False),
        sa.Column(
            "status",
            sa.String(50),
            nullable=False,
            server_default="active",
        ),
        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.Column("updated_by", sa.String(255), nullable=True),
        sa.PrimaryKeyConstraint("id"),
        sa.ForeignKeyConstraint(
            ["parent_id"],
            [f"{_fk('contract_versions')}.id"],
            ondelete="SET NULL",
        ),
        sa.ForeignKeyConstraint(
            ["branch_id"],
            [f"{_fk('branches')}.id"],
            ondelete="SET NULL",
        ),
        schema=schema_name,
    )
    op.create_index(
        "ix_contract_versions_contract_id",
        "contract_versions",
        ["contract_id"],
        schema=schema_name,
    )

    # Add base_version_id FK on branches now that contract_versions exists
    # SQLite does not support ALTER ADD CONSTRAINT; use batch mode (copy-and-move).
    if is_sqlite:
        with op.batch_alter_table("branches", schema=schema_name) as batch_op:
            batch_op.create_foreign_key(
                "fk_branches_base_version_id",
                "contract_versions",
                ["base_version_id"],
                ["id"],
                ondelete="SET NULL",
            )
    else:
        op.create_foreign_key(
            "fk_branches_base_version_id",
            "branches",
            "contract_versions",
            ["base_version_id"],
            ["id"],
            ondelete="SET NULL",
            source_schema=schema_name,
            referent_schema=schema_name,
        )

    # --- proposals ---
    op.create_table(
        "proposals",
        sa.Column("id", uuid_type, nullable=False),
        sa.Column("contract_id", sa.String(255), nullable=False),
        sa.Column("title", sa.String(500), nullable=False),
        sa.Column("description", sa.Text(), nullable=True),
        sa.Column("source_branch_id", uuid_type, nullable=True),
        sa.Column("target_branch_id", uuid_type, nullable=True),
        sa.Column("status", sa.String(50), nullable=False, server_default="open"),
        sa.Column("author", sa.String(255), nullable=False),
        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.Column("updated_by", sa.String(255), nullable=True),
        sa.PrimaryKeyConstraint("id"),
        sa.ForeignKeyConstraint(
            ["source_branch_id"],
            [f"{_fk('branches')}.id"],
            ondelete="SET NULL",
        ),
        sa.ForeignKeyConstraint(
            ["target_branch_id"],
            [f"{_fk('branches')}.id"],
            ondelete="SET NULL",
        ),
        schema=schema_name,
    )
    op.create_index(
        "ix_proposals_contract_id",
        "proposals",
        ["contract_id"],
        schema=schema_name,
    )

    # --- reviews ---
    op.create_table(
        "reviews",
        sa.Column("id", uuid_type, nullable=False),
        sa.Column("proposal_id", uuid_type, nullable=False),
        sa.Column("reviewer", sa.String(255), nullable=False),
        sa.Column("decision", sa.String(50), nullable=False),
        sa.Column("comment", sa.Text(), nullable=True),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=datetime_default,
        ),
        sa.PrimaryKeyConstraint("id"),
        sa.ForeignKeyConstraint(
            ["proposal_id"],
            [f"{_fk('proposals')}.id"],
            ondelete="CASCADE",
        ),
        schema=schema_name,
    )


def downgrade() -> None:
    bind = op.get_bind()
    is_sqlite = bind.dialect.name == "sqlite"
    schema_name = None if is_sqlite else "pycharter"

    # Drop in reverse dependency order
    op.drop_table("reviews", schema=schema_name)
    op.drop_table("proposals", schema=schema_name)

    # Drop the deferred FK on branches before dropping contract_versions
    if not is_sqlite:
        op.drop_constraint(
            "fk_branches_base_version_id",
            "branches",
            type_="foreignkey",
            schema=schema_name,
        )

    op.drop_table("contract_versions", schema=schema_name)
    op.drop_table("branches", schema=schema_name)
    op.drop_table("field_relationships", schema=schema_name)
    op.drop_table("field_concepts", schema=schema_name)
    op.drop_table("fields", schema=schema_name)
    op.drop_table("concepts", schema=schema_name)
