"""Branch name value object with validation."""

from __future__ import annotations

from pydantic import BaseModel, Field, field_validator


class BranchName(BaseModel):
    """Immutable branch name value object."""

    value: str = Field(..., min_length=1, max_length=255, description="Branch name value")

    @field_validator("value")
    @classmethod
    def validate_branch_name(cls, v: str) -> str:
        """Validate branch name follows git conventions.

        Args:
            v: The branch name value to validate

        Returns:
            The validated branch name

        Raises:
            ValueError: If the branch name contains invalid characters
        """
        # Git branch name restrictions
        invalid_chars = ["..", "~", "^", ":", "?", "*", "[", "@{", "\\", " "]

        for char in invalid_chars:
            if char in v:
                raise ValueError(f"Invalid character in branch name: '{char}'")

        # Cannot start or end with certain characters
        if v.startswith(".") or v.startswith("/") or v.endswith(".") or v.endswith("/"):
            raise ValueError("Branch name cannot start or end with '.' or '/'")

        # Cannot contain consecutive slashes
        if "//" in v:
            raise ValueError("Branch name cannot contain consecutive slashes")

        # Cannot be exactly certain reserved names
        reserved_names = ["HEAD", "ORIG_HEAD", "FETCH_HEAD", "MERGE_HEAD"]
        if v.upper() in reserved_names:
            raise ValueError(f"Branch name cannot be a reserved name: {v}")

        return v.strip()

    model_config = {"frozen": True, "extra": "forbid"}

    def __str__(self) -> str:
        """Return the branch name value as string."""
        return self.value

    def __repr__(self) -> str:
        """Return a detailed string representation."""
        return f"BranchName(value='{self.value}')"
