from __future__ import annotations

import uuid
from datetime import datetime
from enum import Enum

from sqlalchemy import DateTime, String, Text
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import Mapped, mapped_column

from core.db.base import Base, SoftDeleteMixin, TimestampMixin


class ScheduleItemStatus(str, Enum):
    ACTIVE = "active"
    COMPLETED = "completed"
    CANCELED = "canceled"
    ARCHIVED = "archived"


class ScheduleItemSourceType(str, Enum):
    MANUAL = "manual"
    IMPORTED = "imported"
    AGENT_GENERATED = "agent_generated"


class ScheduleItem(TimestampMixin, SoftDeleteMixin, Base):
    __tablename__: str = "schedule_items"
    __table_args__ = {"extend_existing": True}

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    owner_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        nullable=False,
    )
    title: Mapped[str] = mapped_column(
        String(255),
        nullable=False,
    )
    description: Mapped[str | None] = mapped_column(
        Text,
        nullable=True,
    )
    start_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        nullable=False,
    )
    end_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True),
        nullable=True,
    )
    timezone: Mapped[str] = mapped_column(
        String(50),
        nullable=False,
        default="UTC",
    )
    extra_metadata: Mapped[dict] = mapped_column(
        "metadata",
        JSONB,
        nullable=False,
        server_default="{}",
    )
    recurrence_rule: Mapped[str | None] = mapped_column(
        String(255),
        nullable=True,
    )
    source_type: Mapped[ScheduleItemSourceType] = mapped_column(
        String(20),
        nullable=False,
        default=ScheduleItemSourceType.MANUAL,
    )
    status: Mapped[ScheduleItemStatus] = mapped_column(
        String(20),
        nullable=False,
        default=ScheduleItemStatus.ACTIVE,
    )
    created_by: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True),
        nullable=True,
    )
