import os

from creative_module.models import AccountSyncLog, AdCreativeData
from creative_module.tasks.ad_creative_task import schedule_onboarding_reconcile, sync_failed_assets
from creative_module.types import UpdateStatus


APPLY = 1
RUN_ID = "a474a5e5-96c9-4e0b-bab4-19febb06bfc8"
AD_CREATIVE_DATA_ID = "02072fc7-2d5d-4538-8cbf-a397e4736074"
STALE_TASK_ID = "0e594420-9509-4aa1-8ac0-259c5508bbbd"

run = AccountSyncLog.objects.select_related("account", "triggered_by").get(id=RUN_ID)
ad = AdCreativeData.objects.get(id=AD_CREATIVE_DATA_ID, account=run.account)

print("Mode:", "APPLY" if APPLY else "DRY RUN")
print(
    "Target:",
    run.account.ad_account_name,
    "run_status=", run.overall_status,
    "ad_status=", ad.sync_status,
    "ad_id=", ad.ad_id,
    "task_id=", ad.task_id,
    "retry_count=", ad.creative_sync_retry_count,
)

assert run.sync_type == AccountSyncLog.SyncType.BACKFILL
assert run.stats_sync_status == AccountSyncLog.StageStatus.SUCCESS
assert ad.sync_status == UpdateStatus.PENDING.value
assert ad.task_id == STALE_TASK_ID

if APPLY:
    # Existing deployed retry helper only selects failed rows, so mark this one
    # stale pending row failed just before handing it to that helper.
    ad.account_sync_log = run
    ad.sync_status = UpdateStatus.FAILED.value
    ad.error_message = "Marked failed manually to requeue stale pending creative fetch"
    ad.save(update_fields=["account_sync_log", "sync_status", "error_message", "updated_at"])

    result = sync_failed_assets(
        run.account_id,
        run.triggered_by_id,
        account_sync_log_id=str(run.id),
        failed_account_sync_log_id=str(run.id),
        retry_entire_failed_sync=False,
        retry_ai_reports=False,
    )
    schedule_onboarding_reconcile(str(run.id))
    ad.refresh_from_db()
    print("Result:", result)
    print("New task_id:", ad.task_id)
    print("New status:", ad.sync_status)
    print("New retry_count:", ad.creative_sync_retry_count)
