import os

from django.db import transaction

from creative_module.models import AccountSyncLog, Report
from creative_module.services.onboarding_service import (
    DEFAULT_AI_REPORT_TITLES,
    refresh_onboarding_run,
)
from creative_module.types import ReportType


APPLY = 1

TARGET_RUNS = {
    "a9190b48-d079-46d8-95d1-2be29f117d99": "ca4026a5-9437-4c06-a776-9dce19351b31",
    "6d89290e-b001-4e84-9666-4e63321c53ac": "32fbf093-8c4e-46e6-8a78-ab07a79e1753",
    "df2900d6-fcff-4667-9269-b4ae5ecd8177": "12d63327-054d-453b-91b8-4cc8c79bb2c2",
    "29ee93e2-c2da-42ba-a6c0-62abb6ced819": "58b3efa0-2977-4a66-9f35-8fc7f163acc5",
    "3fd4b98a-f911-4a81-ae21-e57ae7f6832e": "be48b448-3842-4209-8aba-5834a2af1c07",
    "f570e378-65f5-4cce-b168-782551022bc4": "92ab6eca-426e-4b73-9651-1d27cdd79132",
    "f6621d27-ec8e-48e8-9000-c4c605522601": "b6d79206-490c-479f-9b9c-182e47f7759c",
}

REPORT_TYPES_THAT_SKIP_BOOTSTRAP = {
    ReportType.REGULAR.value,
    ReportType.FATIGUE.value,
    ReportType.FIXER.value,
}


def get_report_counts(run):
    reports = Report.objects.filter(account=run.account, is_deleted=False)
    return {
        "existing_bootstrap_reports": reports.filter(
            type__in=REPORT_TYPES_THAT_SKIP_BOOTSTRAP,
        ).count(),
        "required_ai_reports": reports.filter(
            title__in=DEFAULT_AI_REPORT_TITLES,
        ).count(),
    }


def validate_target(run, expected_account_id):
    problems = []
    if str(run.account_id) != expected_account_id:
        problems.append(f"account mismatch: expected {expected_account_id}, got {run.account_id}")
    if run.sync_type != AccountSyncLog.SyncType.BACKFILL:
        problems.append(f"sync_type is {run.sync_type}, expected BACKFILL")
    if run.stats_sync_status != AccountSyncLog.StageStatus.SUCCESS:
        problems.append(f"stats_sync_status is {run.stats_sync_status}, expected success")
    if run.overall_status == AccountSyncLog.OverallStatus.SUCCESS:
        problems.append("already success")

    counts = get_report_counts(run)
    if counts["existing_bootstrap_reports"] <= 0:
        problems.append("no existing regular/fatigue/fixer reports; this is not the short-circuit case")
    if counts["required_ai_reports"] != 0:
        problems.append(
            f"found {counts['required_ai_reports']} required AI report rows; expected 0 for this repair"
        )

    return problems, counts


def repair_run(run):
    # Setting this first activates the existing backfill freeze branch in the
    # derivation code. refresh_onboarding_run() still derives creative
    # materialization and default overview status before terminal success.
    run.ai_reports_status = AccountSyncLog.StageStatus.SUCCESS
    run.save(update_fields=["ai_reports_status", "updated_at"])
    return refresh_onboarding_run(run)


print(f"Mode: {'APPLY' if APPLY else 'DRY RUN'}")

for run_id, expected_account_id in TARGET_RUNS.items():
    with transaction.atomic():
        run = (
            AccountSyncLog.objects.select_for_update()
            .select_related("account")
            .get(id=run_id)
        )
        before = {
            "overall_status": run.overall_status,
            "current_stage": run.current_stage,
            "ad_creative_sync_status": run.ad_creative_sync_status,
            "stats_sync_status": run.stats_sync_status,
            "ai_reports_status": run.ai_reports_status,
        }
        problems, counts = validate_target(run, expected_account_id)

        if problems:
            print(f"SKIP {run_id} {run.account.ad_account_name}: {'; '.join(problems)}")
            continue

        if APPLY:
            run = repair_run(run)
            after = {
                "overall_status": run.overall_status,
                "current_stage": run.current_stage,
                "ad_creative_sync_status": run.ad_creative_sync_status,
                "stats_sync_status": run.stats_sync_status,
                "ai_reports_status": run.ai_reports_status,
            }
            print(
                f"REPAIRED {run_id} {run.account.ad_account_name}: "
                f"reports={counts}, before={before}, after={after}"
            )
        else:
            print(
                f"WOULD REPAIR {run_id} {run.account.ad_account_name}: "
                f"reports={counts}, before={before}"
            )
