"""Workspace model for persistent writable repo clones."""

from __future__ import annotations

import uuid
from datetime import datetime
from typing import TYPE_CHECKING

from sqlalchemy import DateTime, ForeignKey, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.models.base import Base, TimestampMixin

if TYPE_CHECKING:
    from src.models import GitRepository
    from src.models.user import User


class Workspace(Base, TimestampMixin):
    """A persistent, writable local clone of a Git repository.

    Users create workspaces explicitly, then start tool instances on them.
    Multiple tool instances can share the same workspace.
    """

    __tablename__ = "workspaces"

    id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    repo_id: Mapped[uuid.UUID] = mapped_column(
        ForeignKey("git_repositories.id", ondelete="CASCADE"),
        nullable=False,
    )
    user_id: Mapped[uuid.UUID] = mapped_column(
        ForeignKey("users.id", ondelete="CASCADE"),
        nullable=False,
    )
    branch: Mapped[str] = mapped_column(String(255), nullable=False, default="main")
    path: Mapped[str] = mapped_column(String(2048), nullable=False)
    status: Mapped[str] = mapped_column(String(16), nullable=False, default="ready")
    last_sync_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )

    __table_args__ = (
        UniqueConstraint("repo_id", "name", name="uq_workspace_repo_name"),
    )

    repository: Mapped[GitRepository] = relationship("GitRepository")
    owner: Mapped[User] = relationship("User")
