import json
import logging
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field

logger = logging.getLogger(__name__)
router = APIRouter(tags=["Merge History Mock"])

BASE_DIR = Path(__file__).resolve().parents[2]
MOCK_DIR = BASE_DIR / "static" / "merge_history"
MOCK_FILE = MOCK_DIR / "merge_history_mock.json"


class MergePreviewRequest(BaseModel):
    user_id: str = Field(..., description="The user identity to merge into")
    device_id: str = Field(..., description="The guest device identity")


def _load_mock_data() -> dict[str, Any]:
    """Loads mock JSON data. Synchronous function for thread-pool execution."""
    if not MOCK_FILE.exists():
        raise HTTPException(status_code=404, detail="Mock data file not found")

    try:
        with MOCK_FILE.open("r", encoding="utf-8") as f:
            return json.load(f)
    except json.JSONDecodeError as exc:
        logger.error("Invalid JSON in %s: %s", MOCK_FILE, exc)
        raise HTTPException(status_code=500, detail="Invalid mock JSON format") from exc


@router.get("/api/merge-history/mock", summary="Get merge history mock payload")
def get_merge_history_mock():
    payload = _load_mock_data()
    payload.setdefault("meta", {})["served_at"] = datetime.now(UTC).isoformat()
    return payload


@router.get("/api/merge-history/guest/{device_id}", summary="Get guest timeline by device")
def get_guest_timeline(device_id: str):
    payload = _load_mock_data()
    guest_turns = [turn for turn in payload.get("messages", []) if turn.get("owner_key") == device_id]
    return {
        "status": "success",
        "mode": "guest",
        "identity_key": device_id,
        "total_turns": len(guest_turns),
        "messages": guest_turns,
    }


@router.post("/api/merge-history/preview", summary="Preview merge result for a login action")
def preview_merge(req: MergePreviewRequest):
    payload = _load_mock_data()
    sources = {req.user_id, req.device_id}
    merged_turns = [
        {**turn, "merged_into": req.user_id}
        for turn in payload.get("messages", [])
        if turn.get("owner_key") in sources
    ]
    merged_turns.sort(key=lambda item: item.get("ts", ""))
    return {
        "status": "success",
        "mode": "login_merge_preview",
        "user_id": req.user_id,
        "device_id": req.device_id,
        "total_turns": len(merged_turns),
        "messages": merged_turns,
    }
