"""
Report Agent Scheduler — Multi-job cron-based automated report & insight generation.

Integrates with Hermes Agent cron system for persistent scheduled job management.
Falls back to APScheduler if Hermes core is unavailable.

Job Registry:
  - canifa_daily_sales_report    → 07:00 daily   → Sales summary + trends
  - canifa_weekly_insights       → 09:00 Monday  → Agent performance insights
  - canifa_monthly_trends        → 08:00 1st     → Monthly comparison report
  - canifa_error_watchdog        → every 2h      → Error rate anomaly detection
"""

import asyncio
import logging
import os
import sys
from typing import Dict, List, Optional

logger = logging.getLogger(__name__)

# ─── Hermes Core Integration ────────────────────────────────────────
# Inject hermes-agent-repo to sys.path to access the cron module
HERMES_CORE_PATH = os.path.abspath(
    os.path.join(os.path.dirname(__file__), "../../../hermes-agent-repo")
)

_hermes_available = False

if HERMES_CORE_PATH not in sys.path:
    sys.path.insert(0, HERMES_CORE_PATH)

try:
    from cron.jobs import create_job as hermes_create_job
    _hermes_available = True
    logger.info("Hermes cron module loaded successfully from %s", HERMES_CORE_PATH)
except ImportError as e:
    logger.warning("Hermes cron module not available: %s. Using fallback scheduler.", e)
except Exception as e:
    logger.warning("Hermes cron module error: %s. Using fallback scheduler.", e)


from agent.report_agent.report_queue import enqueue_report_task


# ─── Job Definitions ────────────────────────────────────────────────

JOB_REGISTRY: List[Dict] = [
    {
        "id_suffix": "daily_sales",
        "name": "canifa_daily_sales_report",
        "schedule": "0 7 * * *",
        "prompt": (
            "Tổng hợp báo cáo doanh thu bán hàng ngày hôm qua. "
            "So sánh với cùng kỳ tuần trước. "
            "Phân tích các sản phẩm bán chạy nhất."
        ),
        "question_for_queue": (
            "Tổng hợp báo cáo doanh thu bán hàng ngày hôm qua. "
            "So sánh với cùng kỳ tuần trước. "
            "Phân tích các sản phẩm bán chạy nhất."
        ),
        "conversation_id": "automated-cron-daily-sales",
    },
    {
        "id_suffix": "weekly_insights",
        "name": "canifa_weekly_insights",
        "schedule": "0 9 * * 1",
        "prompt": (
            "Phân tích hiệu suất report agent tuần qua: "
            "tổng sessions, success rate, avg generation time, "
            "top queries, token usage trends. "
            "So sánh với tuần trước và đề xuất cải tiến."
        ),
        "question_for_queue": (
            "Phân tích hiệu suất hệ thống báo cáo tuần qua: "
            "sessions thành công/thất bại, thời gian trung bình, "
            "top câu hỏi phổ biến, xu hướng sử dụng."
        ),
        "conversation_id": "automated-cron-weekly-insights",
    },
    {
        "id_suffix": "monthly_trends",
        "name": "canifa_monthly_trends",
        "schedule": "0 8 1 * *",
        "prompt": (
            "Báo cáo xu hướng tháng: doanh thu, sản phẩm bán chạy, "
            "tồn kho cần bổ sung, hiệu suất nhân viên bán hàng. "
            "So sánh với tháng trước và cùng kỳ năm ngoái."
        ),
        "question_for_queue": (
            "Báo cáo tổng hợp tháng: doanh thu theo chi nhánh, "
            "top sản phẩm, xu hướng tăng/giảm, dự báo tháng tới."
        ),
        "conversation_id": "automated-cron-monthly-trends",
    },
    {
        "id_suffix": "error_watchdog",
        "name": "canifa_error_watchdog",
        "schedule": "every 2h",
        "prompt": (
            "Kiểm tra error rate của report agent 2h qua. "
            "Nếu error rate > 30%, phân tích root cause "
            "và đề xuất khắc phục."
        ),
        "question_for_queue": None,  # This job doesn't enqueue — it's self-contained
        "conversation_id": "automated-cron-error-watchdog",
        "is_watchdog": True,
    },
]


# ─── Automated Report Tasks ────────────────────────────────────────

async def automated_daily_sales_report():
    """
    Automated job to generate daily sales reports.
    Enqueues a report task into the Redis queue for async processing.
    """
    logger.info("Triggering automated daily sales report...")
    question = (
        "Tổng hợp báo cáo doanh thu bán hàng ngày hôm qua. "
        "So sánh với cùng kỳ tuần trước. "
        "Phân tích các sản phẩm bán chạy nhất."
    )

    task_id = await enqueue_report_task(
        question=question,
        model="codex/gpt-5.3-codex",
        conversation_id="automated-cron-daily-sales",
        parent_report_id=None,
        current_html=None,
        codex_token=None,
        openai_key=None,
    )

    if task_id:
        logger.info("Successfully enqueued automated report task: %s", task_id)
    else:
        logger.error("Failed to enqueue automated report task.")


async def automated_weekly_insights():
    """Generate weekly agent performance insights report."""
    logger.info("Triggering automated weekly insights report...")
    try:
        from agent.report_agent.insights_adapter import ReportInsightsEngine

        engine = ReportInsightsEngine()
        report = engine.generate(days=7)
        summary = engine.format_summary(report)

        # Also enqueue as a visible report
        question = (
            "Phân tích hiệu suất hệ thống báo cáo tuần qua: "
            "sessions thành công/thất bại, thời gian trung bình, "
            "top câu hỏi phổ biến, xu hướng sử dụng."
        )
        task_id = await enqueue_report_task(
            question=question,
            model="codex/gpt-5.3-codex",
            conversation_id="automated-cron-weekly-insights",
            parent_report_id=None,
            current_html=None,
            codex_token=None,
            openai_key=None,
        )
        logger.info("Weekly insights: %s (task: %s)", summary[:200], task_id)
    except Exception as e:
        logger.error("Weekly insights failed: %s", e)


async def automated_error_watchdog():
    """Check error rate and generate alert if anomalous."""
    logger.info("Running error watchdog check...")
    try:
        from agent.report_agent.insights_adapter import ReportInsightsEngine

        engine = ReportInsightsEngine()
        report = engine.generate(days=1)  # Last 24h only

        if report.get("empty"):
            logger.info("Watchdog: No sessions in last 24h — healthy")
            return

        anomalies = report.get("anomalies", [])
        critical = [a for a in anomalies if a.get("severity") == "warning"]

        if critical:
            logger.warning(
                "Watchdog ALERT: %d critical anomalies detected: %s",
                len(critical),
                [a["message"] for a in critical],
            )
            # TODO: Send to Telegram/Slack notification channel
        else:
            logger.info("Watchdog: All clear — no anomalies detected")
    except Exception as e:
        logger.error("Error watchdog failed: %s", e)


# ─── Scheduler Startup ──────────────────────────────────────────────

def start_scheduler():
    """
    Register automated report cron jobs.

    Uses Hermes cron.create_job() with the correct API:
        create_job(prompt, schedule, name=..., ...)

    Falls back to a simple asyncio-based scheduler if Hermes is unavailable.
    """
    if _hermes_available:
        _start_hermes_scheduler()
    else:
        _start_fallback_scheduler()


def _start_hermes_scheduler():
    """Register all cron jobs via Hermes Agent cron system."""
    registered = 0
    for job_def in JOB_REGISTRY:
        try:
            hermes_create_job(
                prompt=job_def["prompt"],
                schedule=job_def["schedule"],
                name=job_def["name"],
                deliver="local",
            )
            registered += 1
            logger.info(
                "Hermes Cron registered: '%s' [%s]",
                job_def["name"], job_def["schedule"],
            )
        except Exception as e:
            logger.error(
                "Failed to register Hermes cron job '%s': %s",
                job_def["name"], e,
            )

    if registered == 0:
        logger.warning("No Hermes cron jobs registered — trying fallback")
        _start_fallback_scheduler()
    else:
        logger.info(
            "Hermes Cron: %d/%d jobs registered successfully.",
            registered, len(JOB_REGISTRY),
        )


def _start_fallback_scheduler():
    """Simple asyncio-based fallback when Hermes cron is unavailable."""
    try:
        from apscheduler.schedulers.asyncio import AsyncIOScheduler

        scheduler = AsyncIOScheduler()

        # Daily sales at 07:00
        scheduler.add_job(
            automated_daily_sales_report,
            "cron", hour=7, minute=0,
            id="daily_sales_report",
            replace_existing=True,
        )

        # Weekly insights at Monday 09:00
        scheduler.add_job(
            automated_weekly_insights,
            "cron", day_of_week="mon", hour=9, minute=0,
            id="weekly_insights",
            replace_existing=True,
        )

        # Error watchdog every 2 hours
        scheduler.add_job(
            automated_error_watchdog,
            "interval", hours=2,
            id="error_watchdog",
            replace_existing=True,
        )

        scheduler.start()
        logger.info(
            "Fallback APScheduler started: 3 jobs "
            "(daily_sales 07:00, weekly_insights Mon 09:00, watchdog every 2h)"
        )
    except ImportError:
        logger.warning(
            "Neither Hermes cron nor APScheduler available. "
            "Automated reports will not run."
        )


# ─── Dynamic job registration ───────────────────────────────────────

def register_suggested_jobs() -> int:
    """Register cron jobs suggested by the autonomous curator.

    Returns the number of jobs successfully registered.
    """
    if not _hermes_available:
        logger.info("Hermes cron unavailable — skipping curator suggestions")
        return 0

    try:
        from agent.report_agent.autonomous_loop import ReportCurator

        curator = ReportCurator()
        suggestions = curator.suggest_cron_jobs()
        registered = 0

        for sug in suggestions:
            try:
                hermes_create_job(
                    prompt=sug["prompt"],
                    schedule=sug["schedule"],
                    name=sug["name"],
                    deliver="local",
                )
                registered += 1
                logger.info(
                    "Curator-suggested job registered: '%s' — %s",
                    sug["name"], sug["reason"],
                )
            except Exception as e:
                logger.warning("Failed to register suggested job '%s': %s", sug["name"], e)

        return registered
    except Exception as e:
        logger.warning("Curator job registration failed: %s", e)
        return 0


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    asyncio.run(automated_daily_sales_report())
