"""Versioning API routes."""

from __future__ import annotations

from typing import Any

from fastapi import APIRouter, Depends, HTTPException, Query

from pycharter.wiki.api.dependencies import get_db_session
from pycharter.wiki.api.models.versioning import (
    CreateBranchRequest,
    CreateVersionRequest,
    DiffRequest,
    MergeRequest,
)
from pycharter.wiki.shared.errors import VersioningError
from pycharter.wiki.versioning.diff import compute_ontology_diff
from pycharter.wiki.versioning.history import VersionHistory
from pycharter.wiki.versioning.merge import merge_ontologies

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


@router.post("/versions")
async def create_version(
    request: CreateVersionRequest, session=Depends(get_db_session)
):
    """Create a new ontology version."""
    try:
        vh = VersionHistory(session)
        version_id = vh.create_version(
            contract_id=request.contract_id,
            content=request.content,
            message=request.message,
            author=request.author,
            parent_id=request.parent_id,
            branch_id=request.branch_id,
        )
        return {"version_id": version_id}
    except VersioningError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/versions/{contract_id}/history")
async def get_history(
    contract_id: str,
    branch: str | None = Query(None),
    limit: int = Query(50),
    session=Depends(get_db_session),
):
    """Get version history for a contract."""
    vh = VersionHistory(session)
    versions = vh.get_history(contract_id, branch=branch, limit=limit)
    return [v.to_dict() for v in versions]


@router.get("/versions/{contract_id}/latest")
async def get_latest(
    contract_id: str,
    branch: str | None = Query(None),
    session=Depends(get_db_session),
):
    """Get the latest version for a contract."""
    vh = VersionHistory(session)
    version = vh.get_latest(contract_id, branch=branch)
    if version is None:
        raise HTTPException(status_code=404, detail="No versions found")
    return version.to_dict()


@router.post("/branches")
async def create_branch(request: CreateBranchRequest, session=Depends(get_db_session)):
    """Create a new branch."""
    try:
        vh = VersionHistory(session)
        branch_id = vh.create_branch(
            contract_id=request.contract_id,
            name=request.name,
            base_version_id=request.base_version_id,
            created_by=request.created_by,
        )
        return {"branch_id": branch_id}
    except VersioningError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/branches/{contract_id}")
async def list_branches(contract_id: str, session=Depends(get_db_session)):
    """List all branches for a contract."""
    vh = VersionHistory(session)
    branches = vh.list_branches(contract_id)
    return [b.to_dict() for b in branches]


@router.post("/diff")
async def compute_diff(request: DiffRequest):
    """Compute field-level diff between two ontology versions."""
    diff = compute_ontology_diff(request.old_content, request.new_content)
    return diff.to_dict()


@router.post("/merge")
async def merge(request: MergeRequest):
    """Perform a three-way merge of ontology versions."""
    result = merge_ontologies(request.base, request.ours, request.theirs)
    return result.to_dict()
