from datetime import datetime

from creative_module.models import ReportSections
from creative_module.services.section_service import update_account_sections
from creative_module.types import ReportType
from creative_module.utils import compute_dates_for_key
from organization_auth.models import Account


ACCOUNT_ID = "78aac6a8-e3fa-452f-bd4b-5fbed77a2ec8"


def expected_dates_for_section(section, target_end_date):
    section_config = section.configuration or {}
    report_config = section.report.metadata or {}
    section_date = section_config.get("date") or {}

    if section_date.get("label") == "Custom":
        return None

    date_config = section_date if section_date.get("key") else (report_config.get("date") or {})
    computed = compute_dates_for_key(date_config.get("key"), target_end_date)
    if not computed:
        return None

    return date_config, computed


def count_outdated_sections(account):
    sections = ReportSections.objects.filter(
        account=account,
        report__is_deleted=False,
        report__type__in=[ReportType.REGULAR.value, ReportType.DASHBOARD.value],
    ).select_related("report")

    outdated = 0
    for section in sections:
        result = expected_dates_for_section(section, account.last_synced_date)
        if not result:
            continue

        date_config, (expected_start, expected_end) = result
        if (
            date_config.get("start_date") != expected_start.strftime("%Y-%m-%d")
            or date_config.get("end_date") != expected_end.strftime("%Y-%m-%d")
        ):
            outdated += 1

    return outdated


account = Account.objects.get(id=ACCOUNT_ID)
print(f"account={account.id} name={account.ad_account_name!r} version={account.version} is_demo={account.is_demo}")
print(f"first_synced_date={account.first_synced_date} last_synced_date={account.last_synced_date}")
print(f"outdated_before={count_outdated_sections(account)}")

started_at = datetime.now()
result = update_account_sections(account=account)
print(f"result={result}")
print(f"elapsed_seconds={(datetime.now() - started_at).total_seconds():.2f}")

account.refresh_from_db()
print(f"outdated_after={count_outdated_sections(account)}")
