"""Lazy compatibility helpers for legacy single-process development.

Production scheduling belongs to ``momo-scheduler``. Keeping scheduler imports
inside these functions prevents every Gunicorn worker from loading crawler and
AI task dependencies during web startup.
"""

from __future__ import annotations

import importlib
import threading
import time
from datetime import datetime
from typing import Callable


def run_schedule(logger) -> None:
    import schedule

    logger.info("Legacy local scheduler loop started")
    while True:
        schedule.run_pending()
        time.sleep(1)


def init_scheduler(logger) -> threading.Thread:
    """Register the legacy development schedule without eager web imports."""
    import schedule
    from scheduler import (
        run_auto_import_task,
        run_competitor_price_feeder_task,
        run_edm_task,
        run_festival_task,
        run_momo_task,
        run_pchome_match_backfill_task,
        run_whitepage_check,
    )

    schedule.every(1).hours.do(run_momo_task)
    schedule.every(1).hours.do(run_edm_task)
    schedule.every(1).hours.do(run_festival_task)
    schedule.every(30).minutes.do(run_auto_import_task)
    schedule.every(30).minutes.do(run_whitepage_check)
    schedule.every(4).hours.do(run_competitor_price_feeder_task)
    schedule.every().day.at("10:30").do(run_pchome_match_backfill_task)

    scheduler_thread = threading.Thread(
        target=run_schedule,
        args=(logger,),
        daemon=True,
        name="legacy-web-scheduler",
    )
    scheduler_thread.start()
    logger.info("Legacy local scheduler registered; production remains delegated")
    return scheduler_thread


def scheduled_job_wrapper(logger, dashboard_stats_getter: Callable[[], dict]) -> threading.Thread:
    """Run the legacy MOMO command in a background thread on explicit request."""
    timestamp = datetime.now().strftime("%H:%M:%S")
    logger.info("Legacy MOMO command started at %s", timestamp)

    def job() -> None:
        from scheduler import run_momo_task

        run_momo_task()
        try:
            scheduler_module = importlib.import_module("scheduler")
            notification_module = importlib.import_module("services.notification_manager")
            importlib.reload(scheduler_module)
            importlib.reload(notification_module)
            notification_manager = notification_module.NotificationManager
            stats = dashboard_stats_getter()
            if any(stats.values()):
                screenshot_path = scheduler_module.capture_page_screenshot(
                    "http://127.0.0.1/",
                    "momo_dashboard",
                )
                notification_manager().send_momo_report(stats, screenshot_path)
        except Exception as exc:
            logger.error("Legacy scheduler notification failed: %s", exc)

    worker = threading.Thread(
        target=job,
        daemon=True,
        name="legacy-momo-command",
    )
    worker.start()
    return worker


__all__ = ["init_scheduler", "run_schedule", "scheduled_job_wrapper"]
