# -*- coding: utf-8 -*-
"""调度配置 Pydantic 模型

定义 ScheduleConfigSchema 及相关模型，供调度服务和路由使用。
"""

from datetime import datetime
from typing import Any, Literal

from pydantic import BaseModel


class ScheduleConfigSchema(BaseModel):
    """调度配置 — 支持 5 种调度类型"""

    schedule_type: Literal["once", "interval", "daily", "weekly", "cron"]
    interval_value: int = 1
    interval_unit: Literal["minutes", "hours", "days"] = "hours"
    daily_time: str = "04:00"
    weekly_days: list[int] = [1]
    weekly_time: str = "04:00"
    cron_expression: str = "0 4 * * *"
    enabled: bool = True
    start_date: str | None = None
    end_date: str | None = None


class MinRunIntervalItem(BaseModel):
    """单个任务的最小执行间隔"""

    value: int = 0
    unit: Literal["minutes", "hours", "days"] = "minutes"


class CreateScheduleRequest(BaseModel):
    """创建调度任务请求"""

    name: str
    task_codes: list[str]
    task_config: dict[str, Any]
    schedule_config: ScheduleConfigSchema
    run_immediately: bool = False
    min_run_interval_value: int = 0  # 0 表示无限制（schedule 级别默认）
    min_run_interval_unit: Literal["minutes", "hours", "days"] = "minutes"
    min_run_intervals: dict[str, MinRunIntervalItem] = {}  # per-task-code 间隔


class UpdateScheduleRequest(BaseModel):
    """更新调度任务请求（所有字段可选）"""

    name: str | None = None
    task_codes: list[str] | None = None
    task_config: dict[str, Any] | None = None
    schedule_config: ScheduleConfigSchema | None = None
    min_run_interval_value: int | None = None
    min_run_interval_unit: Literal["minutes", "hours", "days"] | None = None
    min_run_intervals: dict[str, MinRunIntervalItem] | None = None


class ScheduleResponse(BaseModel):
    """调度任务响应"""

    id: str
    site_id: int
    name: str
    task_codes: list[str]
    task_config: dict[str, Any]
    schedule_config: dict[str, Any]
    enabled: bool
    last_run_at: datetime | None = None
    next_run_at: datetime | None = None
    run_count: int
    last_status: str | None = None
    min_run_interval_value: int = 0
    min_run_interval_unit: str = "minutes"
    last_success_at: datetime | None = None
    min_run_intervals: dict[str, Any] = {}
    created_at: datetime
    updated_at: datetime
