from __future__ import annotations

from datetime import datetime
from uuid import UUID

from pydantic import BaseModel, ConfigDict, Field


# ── Document ─────────────────────────────────────────────────────


class DocumentCreate(BaseModel):
    """Payload for creating a new reference document."""

    slug: str = Field(..., min_length=1, max_length=128)
    title: str = Field(..., min_length=1, max_length=256)
    doc_type: str = Field(..., max_length=64, description="licence, engagement, reglement, constitution")
    description: str | None = None
    version: str | None = Field(default="0.1.0", max_length=32)


class DocumentUpdate(BaseModel):
    """Partial update for a document."""

    title: str | None = Field(default=None, max_length=256)
    status: str | None = Field(default=None, max_length=32)
    description: str | None = None
    version: str | None = Field(default=None, max_length=32)


class DocumentOut(BaseModel):
    """Full document representation returned by the API."""

    model_config = ConfigDict(from_attributes=True)

    id: UUID
    slug: str
    title: str
    doc_type: str
    version: str
    status: str
    description: str | None = None
    ipfs_cid: str | None = None
    chain_anchor: str | None = None
    genesis_json: str | None = None
    created_at: datetime
    updated_at: datetime
    items_count: int = Field(default=0, description="Number of items in this document")


# ── Document Item ────────────────────────────────────────────────


class DocumentItemCreate(BaseModel):
    """Payload for creating a document item (clause, rule, etc.)."""

    position: str = Field(..., max_length=16, description='Hierarchical position e.g. "1", "1.1", "3.2"')
    item_type: str = Field(default="clause", max_length=32, description="clause, rule, verification, preamble, section, genesis")
    title: str | None = Field(default=None, max_length=256)
    current_text: str = Field(..., min_length=1)
    voting_protocol_id: UUID | None = None
    section_tag: str | None = Field(default=None, max_length=64)
    inertia_preset: str = Field(default="standard", max_length=16)
    is_permanent_vote: bool = True


class DocumentItemUpdate(BaseModel):
    """Partial update for a document item."""

    title: str | None = Field(default=None, max_length=256)
    current_text: str | None = Field(default=None, min_length=1)
    position: str | None = Field(default=None, max_length=16)
    item_type: str | None = Field(default=None, max_length=32)


class DocumentItemOut(BaseModel):
    """Full document item representation."""

    model_config = ConfigDict(from_attributes=True)

    id: UUID
    document_id: UUID
    position: str
    item_type: str
    title: str | None = None
    current_text: str
    voting_protocol_id: UUID | None = None
    sort_order: int
    section_tag: str | None = None
    inertia_preset: str = "standard"
    is_permanent_vote: bool = True
    created_at: datetime
    updated_at: datetime


class DocumentItemFullOut(BaseModel):
    """Document item with its full version history."""

    model_config = ConfigDict(from_attributes=True)

    id: UUID
    document_id: UUID
    position: str
    item_type: str
    title: str | None = None
    current_text: str
    voting_protocol_id: UUID | None = None
    sort_order: int
    section_tag: str | None = None
    inertia_preset: str = "standard"
    is_permanent_vote: bool = True
    created_at: datetime
    updated_at: datetime
    versions: list[ItemVersionOut] = Field(default_factory=list)


class DocumentFullOut(BaseModel):
    """Document with full items list (not just count)."""

    model_config = ConfigDict(from_attributes=True)

    id: UUID
    slug: str
    title: str
    doc_type: str
    version: str
    status: str
    description: str | None = None
    ipfs_cid: str | None = None
    chain_anchor: str | None = None
    genesis_json: str | None = None
    created_at: datetime
    updated_at: datetime
    items: list[DocumentItemOut] = Field(default_factory=list)


# ── Item Reorder ─────────────────────────────────────────────────


class ItemReorderEntry(BaseModel):
    """A single item reorder entry."""

    item_id: UUID
    sort_order: int = Field(..., ge=0)


class ItemReorderRequest(BaseModel):
    """Payload for reordering items in a document."""

    items: list[ItemReorderEntry]


# ── Item Version ─────────────────────────────────────────────────


class ItemVersionCreate(BaseModel):
    """Payload for proposing a new version of a document item."""

    proposed_text: str = Field(..., min_length=1)
    rationale: str | None = None


class ItemVersionOut(BaseModel):
    """Full item version representation."""

    model_config = ConfigDict(from_attributes=True)

    id: UUID
    item_id: UUID
    proposed_text: str
    diff_text: str | None = None
    rationale: str | None = None
    status: str
    decision_id: UUID | None = None
    proposed_by_id: UUID | None = None
    created_at: datetime


# ── Forward reference resolution ─────────────────────────────────
# DocumentItemFullOut references ItemVersionOut which is defined after it.
# With `from __future__ import annotations`, Pydantic needs explicit rebuild.

DocumentItemFullOut.model_rebuild()
DocumentFullOut.model_rebuild()
