"""Proposals API routes."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Query

from pycharter.wiki.api.dependencies import get_db_session
from pycharter.wiki.api.models.proposals import (
    CreateProposalRequest,
    UpdateProposalStatusRequest,
)
from pycharter.wiki.collaboration.proposals import ProposalManager
from pycharter.wiki.shared.errors import CollaborationError

router = APIRouter(tags=["Wiki"])


@router.post("/")
async def create_proposal(
    request: CreateProposalRequest, session=Depends(get_db_session)
):
    """Create a new proposal."""
    try:
        pm = ProposalManager(session)
        proposal_id = pm.create_proposal(
            contract_id=request.contract_id,
            title=request.title,
            author=request.author,
            description=request.description,
            source_branch_id=request.source_branch_id,
            target_branch_id=request.target_branch_id,
        )
        return {"proposal_id": proposal_id}
    except CollaborationError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/{proposal_id}")
async def get_proposal(proposal_id: str, session=Depends(get_db_session)):
    """Get a proposal by ID."""
    pm = ProposalManager(session)
    proposal = pm.get_proposal(proposal_id)
    if proposal is None:
        raise HTTPException(status_code=404, detail="Proposal not found")
    return proposal


@router.get("/contract/{contract_id}")
async def list_proposals(
    contract_id: str,
    status: str | None = Query(None),
    session=Depends(get_db_session),
):
    """List proposals for a contract."""
    pm = ProposalManager(session)
    return pm.list_proposals(contract_id, status=status)


@router.put("/{proposal_id}/status")
async def update_status(
    proposal_id: str,
    request: UpdateProposalStatusRequest,
    session=Depends(get_db_session),
):
    """Update a proposal's status."""
    try:
        pm = ProposalManager(session)
        pm.update_status(proposal_id, request.status, updated_by=request.updated_by)
        return {"status": "updated"}
    except CollaborationError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/{proposal_id}/merge")
async def merge_proposal(
    proposal_id: str,
    merged_by: str = Query(...),
    session=Depends(get_db_session),
):
    """Merge a proposal."""
    try:
        pm = ProposalManager(session)
        pm.merge_proposal(proposal_id, merged_by)
        return {"status": "merged"}
    except CollaborationError as e:
        raise HTTPException(status_code=400, detail=str(e))
