from __future__ import annotations

import uuid
import time
from datetime import datetime, timezone
from typing import Any, Dict, Optional


def _new_id() -> str:
    return str(uuid.uuid4())


def _now_ms() -> int:
    return int(time.time() * 1000)


def _utc_str(dt: datetime) -> str:
    if dt.tzinfo is None:
        raise ValueError("datetime must be timezone-aware")
    return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def build_reminder_task_name(prefix: str, target_id: str, remind_at_utc: datetime) -> str:
    suffix = remind_at_utc.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    return "store-{}-{}-{}".format(prefix, target_id, suffix)


def build_reminder_task(
    name: str,
    remind_at_utc: datetime,
    message: str,
) -> Dict[str, Any]:
    now = _now_ms()
    return {
        "id": _new_id(),
        "name": name,
        "enabled": True,
        "deleteAfterRun": True,
        "createdAtMs": now,
        "updatedAtMs": now,
        "schedule": {
            "kind": "at",
            "at": _utc_str(remind_at_utc),
        },
        "sessionTarget": "main",
        "wakeMode": "next-heartbeat",
        "payload": {
            "kind": "systemEvent",
            "message": message,
        },
    }


def build_cron_task(
    name: str,
    cron_expr: str,
    message: str,
    *,
    tz: str = "Asia/Shanghai",
    delete_after_run: bool = False,
) -> Dict[str, Any]:
    now = _now_ms()
    job: Dict[str, Any] = {
        "id": _new_id(),
        "name": name,
        "enabled": True,
        "createdAtMs": now,
        "updatedAtMs": now,
        "schedule": {
            "kind": "cron",
            "expr": cron_expr,
            "tz": tz,
        },
        "sessionTarget": "main",
        "wakeMode": "next-heartbeat",
        "payload": {
            "kind": "systemEvent",
            "message": message,
        },
    }
    if delete_after_run:
        job["deleteAfterRun"] = True
    return job


def build_report_task(
    name: str,
    message: str,
    *,
    cron_expr: Optional[str] = None,
    tz: str = "Asia/Shanghai",
    delete_after_run: bool = False,
) -> Dict[str, Any]:
    if not cron_expr:
        raise ValueError("cron_expr is required")
    now = _now_ms()
    job: Dict[str, Any] = {
        "id": _new_id(),
        "name": name,
        "enabled": True,
        "createdAtMs": now,
        "updatedAtMs": now,
        "schedule": {
            "kind": "cron",
            "expr": cron_expr,
            "tz": tz,
        },
        "sessionTarget": "isolated",
        "wakeMode": "next-heartbeat",
        "payload": {
            "kind": "agentTurn",
            "message": message,
        },
        "delivery": {"mode": "announce", "channel": "last"},
    }
    if delete_after_run:
        job["deleteAfterRun"] = True
    return job
