-- 区分正式日报、手工运行与历史重建的运行语义

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'daily_report' AND column_name = 'run_kind'
    ) THEN
        ALTER TABLE daily_report ADD COLUMN run_kind TEXT NOT NULL DEFAULT 'scheduled';
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'daily_report' AND column_name = 'trigger_source'
    ) THEN
        ALTER TABLE daily_report ADD COLUMN trigger_source TEXT NOT NULL DEFAULT 'legacy_backfill';
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'daily_report' AND column_name = 'is_official_daily'
    ) THEN
        ALTER TABLE daily_report ADD COLUMN is_official_daily BOOLEAN NOT NULL DEFAULT TRUE;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'report_runs' AND column_name = 'run_kind'
    ) THEN
        ALTER TABLE report_runs ADD COLUMN run_kind TEXT NOT NULL DEFAULT 'unknown';
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'report_runs' AND column_name = 'trigger_source'
    ) THEN
        ALTER TABLE report_runs ADD COLUMN trigger_source TEXT NOT NULL DEFAULT 'legacy_backfill';
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'report_runs' AND column_name = 'is_official_daily'
    ) THEN
        ALTER TABLE report_runs ADD COLUMN is_official_daily BOOLEAN NOT NULL DEFAULT FALSE;
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_daily_report_official_daily ON daily_report(is_official_daily);
CREATE INDEX IF NOT EXISTS idx_daily_report_run_kind ON daily_report(run_kind);
CREATE INDEX IF NOT EXISTS idx_report_runs_run_kind ON report_runs(run_kind);
CREATE INDEX IF NOT EXISTS idx_report_runs_official_daily ON report_runs(is_official_daily);
