from pathlib import Path
from typing import Optional

from pydantic import BaseModel, Field

DEFAULT_RECORDINGS_DIR = str(Path(__file__).resolve().parents[2] / "mediamtx" / "recordings")


class Camera(BaseModel):
  name: str = Field(min_length=1, max_length=64, pattern=r"^[a-zA-Z0-9_\-\/]+$")
  rtsp_url: str = Field(min_length=1, max_length=2048)


class Schedule(BaseModel):
  enabled: bool = True
  weekdays_from: str = Field(default="18:00", pattern=r"^\d{2}:\d{2}$")
  weekdays_to: str = Field(default="08:00", pattern=r"^\d{2}:\d{2}$")
  weekend_all_day: bool = True


class AppConfig(BaseModel):
  mediamtx_api_url: str = "http://127.0.0.1:9997"
  mediamtx_webrtc_url: str = "http://127.0.0.1:8889"
  mediamtx_api_user: Optional[str] = None
  mediamtx_api_pass: Optional[str] = None
  recordings_dir: str = DEFAULT_RECORDINGS_DIR
  api_port: int = 8008
  cameras: list[Camera] = Field(default_factory=list)
  schedule: Schedule = Field(default_factory=Schedule)


class AppConfigUpdate(BaseModel):
  mediamtx_api_url: str = Field(min_length=1, max_length=2048)
  mediamtx_webrtc_url: str = Field(min_length=1, max_length=2048)
  mediamtx_api_user: Optional[str] = None
  mediamtx_api_pass: Optional[str] = None
  recordings_dir: str = Field(min_length=1, max_length=4096)
  api_port: int = Field(ge=1, le=65535, default=8008)


class RecordingToggle(BaseModel):
  enabled: bool


class SchedulerEnabled(BaseModel):
  enabled: bool


class ScheduleUpdate(BaseModel):
  weekdays_from: str = Field(pattern=r"^\d{2}:\d{2}$")
  weekdays_to: str = Field(pattern=r"^\d{2}:\d{2}$")
  weekend_all_day: bool


class MediaMTXCamera(BaseModel):
  name: str
  rtsp_url: str


class MediaMTXConfigView(BaseModel):
  api_url: str
  webrtc_url: str
  record_enabled: bool
  record_delete_after_days: Optional[int] = None
  cameras: list[MediaMTXCamera]


class MediaMTXAddCameraRequest(BaseModel):
  rtsp_url: str = Field(min_length=1, max_length=2048)


class RecordDeleteAfterUpdate(BaseModel):
  days: int = Field(ge=1, le=7)
