"""OpenClaw jobs owned by the dedicated scheduler runtime."""

from __future__ import annotations

import importlib
import logging
from typing import Any


LOGGER = logging.getLogger(__name__)
JOB_TAG = "openclaw-dedicated-runtime"


def run_openclaw_job(job_name: str) -> dict[str, Any]:
    """Lazy-load the large bot route module only when a job is due."""
    try:
        bot_routes = importlib.import_module("routes.openclaw_bot_routes")
        job = getattr(bot_routes, job_name)
        result = job()
        return {"status": "completed", "job": job_name, "result": result}
    except Exception as exc:
        LOGGER.exception("OpenClaw scheduled job failed: %s", job_name)
        return {
            "status": "failed",
            "job": job_name,
            "error_kind": type(exc).__name__,
        }


def run_data_freshness_job() -> dict[str, Any]:
    try:
        probe = importlib.import_module("services.data_freshness_probe")
        result = probe.run_data_freshness_probe()
        return {"status": "completed", "job": "run_data_freshness_probe", "result": result}
    except Exception as exc:
        LOGGER.exception("OpenClaw data freshness job failed")
        return {
            "status": "failed",
            "job": "run_data_freshness_probe",
            "error_kind": type(exc).__name__,
        }


def register_openclaw_schedules(schedule_module, logger=LOGGER) -> list:
    """Register every OpenClaw timed job exactly once in momo-scheduler."""
    jobs = [
        schedule_module.every().day.at("08:00").do(
            run_openclaw_job,
            "send_competitor_report",
        ),
        schedule_module.every().day.at("08:30").do(
            run_openclaw_job,
            "send_morning_report",
        ),
        schedule_module.every().day.at("08:45").do(
            run_openclaw_job,
            "send_daily_excel",
        ),
        schedule_module.every().day.at("21:00").do(
            run_openclaw_job,
            "send_evening_report",
        ),
        schedule_module.every().monday.at("09:00").do(
            run_openclaw_job,
            "send_weekly_report",
        ),
        schedule_module.every().day.at("09:00").do(
            run_openclaw_job,
            "check_anomalies",
        ),
        schedule_module.every().day.at("12:00").do(
            run_openclaw_job,
            "check_anomalies",
        ),
        schedule_module.every().day.at("15:00").do(
            run_openclaw_job,
            "check_anomalies",
        ),
        schedule_module.every().day.at("18:00").do(
            run_openclaw_job,
            "check_anomalies",
        ),
        schedule_module.every().day.at("09:05").do(run_data_freshness_job),
    ]
    for job in jobs:
        job.tag(JOB_TAG)
    logger.info("Registered %s OpenClaw jobs in momo-scheduler", len(jobs))
    return jobs


__all__ = [
    "JOB_TAG",
    "register_openclaw_schedules",
    "run_data_freshness_job",
    "run_openclaw_job",
]
