"""v0.3 — sbom_entries table + managed_repos SBOM columns

Adds software bill-of-materials tracking: per-repo dependency snapshots with
package name, version, ecosystem, SPDX licence, and direct/dev flags.
Also adds sbom_source and last_sbom_at to managed_repos.

Revision ID: d3e4f5a6b7c8
Revises: c2d3e4f5a6b7
Create Date: 2026-02-28 00:00:00.000000
"""
from typing import Sequence, Union

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

revision: str = "d3e4f5a6b7c8"
down_revision: Union[str, None] = "c2d3e4f5a6b7"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Add SBOM-related columns to managed_repos
    op.add_column("managed_repos", sa.Column("sbom_source", sa.Text, nullable=True))
    op.add_column("managed_repos",
                  sa.Column("last_sbom_at", sa.DateTime(timezone=True), nullable=True))

    ecosystem_enum = postgresql.ENUM(
        "python", "node", "rust", "go", "java", "other",
        name="ecosystem", create_type=True,
    )

    op.create_table(
        "sbom_entries",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True,
                  server_default=sa.text("gen_random_uuid()")),
        sa.Column("repo_id", postgresql.UUID(as_uuid=True),
                  sa.ForeignKey("managed_repos.id", ondelete="RESTRICT"), nullable=False),
        sa.Column("package_name", sa.String(300), nullable=False),
        sa.Column("package_version", sa.String(100), nullable=True),
        sa.Column("ecosystem", ecosystem_enum, nullable=False),
        sa.Column("license_spdx", sa.String(100), nullable=True),
        sa.Column("is_direct", sa.Boolean, nullable=False, server_default="true"),
        sa.Column("is_dev", sa.Boolean, nullable=False, server_default="false"),
        sa.Column("snapshot_at", sa.DateTime(timezone=True),
                  server_default=sa.text("now()"), nullable=False),
        sa.Column("created_at", sa.DateTime(timezone=True),
                  server_default=sa.text("now()"), nullable=False),
    )
    op.create_index("ix_sbom_entries_repo_id", "sbom_entries", ["repo_id"])
    op.create_index("ix_sbom_entries_package_name", "sbom_entries", ["package_name"])
    op.create_index("ix_sbom_entries_license_spdx", "sbom_entries", ["license_spdx"])


def downgrade() -> None:
    op.drop_table("sbom_entries")
    op.execute("DROP TYPE IF EXISTS ecosystem")
    op.drop_column("managed_repos", "last_sbom_at")
    op.drop_column("managed_repos", "sbom_source")
