from __future__ import annotations

from sqlalchemy.engine import Connection, Engine

from app.db.base import Base

MIGRATION_OWNED_TABLES: frozenset[str] = frozenset(
    {
        "auth_sessions",
        "approval_action_ledgers",
        "approval_task_events",
        "approval_tasks",
        "agent_asset_release_audit_samples",
        "agent_asset_release_labels",
        "agent_asset_release_observations",
        "attachment_association_jobs",
        "ai_application_preview_decisions",
        "ai_decisions",
        "ai_decision_feedback",
        "expense_cases",
        "expense_case_links",
        "business_events",
        "financial_connector_configs",
        "financial_connector_config_events",
        "financial_connector_events",
        "financial_connector_operational_events",
        "commercial_cost_events",
        "commercial_admin_events",
        "commercial_billing_periods",
        "commercial_entitlements",
        "commercial_runtime_reservations",
        "knowledge_onlyoffice_sessions",
        "memory_entries",
        "memory_evidence_links",
        "risk_observations",
        "risk_observation_feedback",
        "risk_dispositions",
        "risk_disposition_events",
        "profile_baseline_snapshots",
        "payment_reconciliation_cases",
        "payment_reconciliation_events",
        "savings_opportunities",
        "savings_realizations",
        "savings_evidence_links",
        "savings_events",
        "tenant_commercial_plans",
        "tenant_finance_report_configs",
        "tenant_finance_report_runs",
        "tenant_subscriptions",
        "tenants",
        "usage_meter_events",
        "few_shot_samples",
        "workflow_outcomes",
    }
)


def create_legacy_schema(bind: Engine | Connection) -> None:
    """创建仍由旧 bootstrap 管理的表，不越过 Alembic 的表所有权边界。"""
    legacy_tables = [
        table for table in Base.metadata.sorted_tables if table.name not in MIGRATION_OWNED_TABLES
    ]
    Base.metadata.create_all(bind=bind, tables=legacy_tables)
