"""Add compliance_results + compliance_checks tables for Wazuh SCA

Revision ID: 016
Revises: 015
Create Date: 2026-05-19 09:00:00.000000

Two-table layout:

- compliance_results: per (asset, policy) summary — score, totals,
  scan timestamps. One row per pair, overwritten on refresh.
- compliance_checks:  per individual check, only populated when the
  deep-dive endpoint is hit.

Both tables idempotent via IF NOT EXISTS so the migration is safe to
re-run.
"""
from alembic import op
import sqlalchemy as sa


revision = '016'
down_revision = '015'
branch_labels = None
depends_on = None


def upgrade() -> None:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    existing = set(inspector.get_table_names())

    if "compliance_results" not in existing:
        op.create_table(
            "compliance_results",
            sa.Column("id", sa.Integer(), primary_key=True),
            sa.Column("asset_id", sa.Integer(),
                      sa.ForeignKey("assets.id", ondelete="CASCADE"),
                      nullable=False),
            sa.Column("policy_id", sa.String(64), nullable=False),
            sa.Column("policy_name", sa.String(255), nullable=True),
            sa.Column("policy_description", sa.Text(), nullable=True),
            sa.Column("total_checks", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("pass_count", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("fail_count", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("not_applicable_count", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("score", sa.Float(), nullable=True),
            sa.Column("end_scan", sa.DateTime(), nullable=True),
            sa.Column("last_synced", sa.DateTime(), nullable=False,
                      server_default=sa.text("now()")),
            sa.Column("created_at", sa.DateTime(), nullable=False,
                      server_default=sa.text("now()")),
            sa.Column("updated_at", sa.DateTime(), nullable=False,
                      server_default=sa.text("now()")),
            sa.UniqueConstraint("asset_id", "policy_id",
                                name="uq_compliance_asset_policy"),
        )
        op.create_index("ix_compliance_results_asset_id",
                        "compliance_results", ["asset_id"])
        op.create_index("ix_compliance_results_policy_id",
                        "compliance_results", ["policy_id"])
        op.create_index("ix_compliance_score_desc",
                        "compliance_results", ["score"])

    if "compliance_checks" not in existing:
        op.create_table(
            "compliance_checks",
            sa.Column("id", sa.Integer(), primary_key=True),
            sa.Column("result_id", sa.Integer(),
                      sa.ForeignKey("compliance_results.id", ondelete="CASCADE"),
                      nullable=False),
            sa.Column("check_id", sa.String(64), nullable=False),
            sa.Column("title", sa.String(500), nullable=True),
            sa.Column("description", sa.Text(), nullable=True),
            sa.Column("rationale", sa.Text(), nullable=True),
            sa.Column("remediation", sa.Text(), nullable=True),
            sa.Column("result", sa.String(20), nullable=False),
            sa.Column("severity", sa.String(20), nullable=True),
            sa.Column("created_at", sa.DateTime(), nullable=False,
                      server_default=sa.text("now()")),
            sa.Column("updated_at", sa.DateTime(), nullable=False,
                      server_default=sa.text("now()")),
        )
        op.create_index("ix_compliance_checks_result_id",
                        "compliance_checks", ["result_id"])
        op.create_index("ix_compliance_check_result_result",
                        "compliance_checks", ["result_id", "result"])
        op.create_index("ix_compliance_checks_result",
                        "compliance_checks", ["result"])


def downgrade() -> None:
    op.execute("DROP TABLE IF EXISTS compliance_checks")
    op.execute("DROP TABLE IF EXISTS compliance_results")
