import uuid
import enum
from datetime import date, datetime, time
from typing import TYPE_CHECKING

from sqlalchemy import Date, DateTime, Enum, ForeignKey, Integer, String, Text, Time, func
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.database import Base

if TYPE_CHECKING:
    from app.models.user import User


class EntryStatus(str, enum.Enum):
    PENDING = "pending"
    APPROVED = "approved"
    REJECTED = "rejected"


class EntrySource(str, enum.Enum):
    WEB = "web"
    KIOSK = "kiosk"
    API = "api"
    MANUAL = "manual"


class TimeEntry(Base):
    __tablename__ = "time_entries"

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    user_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
    )
    date: Mapped[date] = mapped_column(Date, nullable=False, index=True)
    start_time: Mapped[time] = mapped_column(Time(timezone=False), nullable=False)
    end_time: Mapped[time | None] = mapped_column(Time(timezone=False))
    break_minutes: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default="0")
    break_start: Mapped[time | None] = mapped_column(Time(timezone=False))  # Aktive Pause tracken
    project_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True))
    note: Mapped[str | None] = mapped_column(Text)
    status: Mapped[EntryStatus] = mapped_column(
        Enum(EntryStatus, name="entrystatus", values_callable=lambda x: [e.value for e in x]), nullable=False, default=EntryStatus.PENDING
    )
    source: Mapped[EntrySource] = mapped_column(
        Enum(EntrySource, name="entrysource", values_callable=lambda x: [e.value for e in x]), nullable=False, default=EntrySource.WEB
    )
    approved_by: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL")
    )
    correction_note: Mapped[str | None] = mapped_column(Text)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())

    user: Mapped["User"] = relationship(
        "User", primaryjoin="TimeEntry.user_id == User.id",
        foreign_keys="[TimeEntry.user_id]", lazy="noload"
    )
    approver: Mapped["User | None"] = relationship(
        "User", primaryjoin="TimeEntry.approved_by == User.id",
        foreign_keys="[TimeEntry.approved_by]", lazy="noload"
    )
    @property
    def worked_minutes(self) -> int | None:
        """Gearbeitete Minuten (ohne Pausen), None wenn noch offen."""
        if self.end_time is None:
            return None
        # Sekunden einbeziehen um Sub-Minuten-Einträge korrekt zu behandeln
        # (z.B. Einstemp+Ausstemp in derselben Minute → soll 0h zeigen, nicht 24h)
        start_secs = (self.start_time.hour * 3600
                      + self.start_time.minute * 60
                      + self.start_time.second)
        end_secs = (self.end_time.hour * 3600
                    + self.end_time.minute * 60
                    + self.end_time.second)
        if end_secs < start_secs:
            end_secs += 24 * 3600  # Nachtschicht (Ende am nächsten Tag)
        total_mins = (end_secs - start_secs) // 60
        return max(0, total_mins - self.break_minutes)

    @property
    def worked_hours(self) -> float | None:
        mins = self.worked_minutes
        return round(mins / 60, 2) if mins is not None else None

    def __repr__(self) -> str:
        return f"<TimeEntry {self.user_id} {self.date} {self.start_time}-{self.end_time}>"
