from __future__ import annotations

from pathlib import Path
from typing import Any

from liverylab_core import runtime_profiles


RUNTIME_LABELS = {
    runtime_profiles.RUNTIME_OFFICIAL: "Official mode",
    runtime_profiles.RUNTIME_ADVANCED: "Advanced/extracted mode",
    runtime_profiles.RUNTIME_MIXED: "Mixed state",
    runtime_profiles.RUNTIME_UNKNOWN: "Unknown state",
}


def _runtime_label(value: Any) -> str:
    key = str(value or runtime_profiles.RUNTIME_UNKNOWN).strip().lower()
    return RUNTIME_LABELS.get(key, "Unknown state")


def _message_lines(state: dict[str, Any]) -> list[str]:
    lines: list[str] = []
    blockers = state.get("blockers") if isinstance(state.get("blockers"), list) else []
    warnings = state.get("warnings") if isinstance(state.get("warnings"), list) else []
    reasons = state.get("reasons") if isinstance(state.get("reasons"), list) else []
    if blockers:
        lines.extend(f"Blocker: {item}" for item in blockers[:4])
    if warnings:
        lines.extend(f"Warning: {item}" for item in warnings[:4])
    if reasons:
        lines.extend(f"Signal: {item}" for item in reasons[:5])
    return lines


def assert_advanced_game_writes_ready(
    game_root: str | Path | None,
    *,
    saved_games_ace_root: str | Path | None = None,
    package_manifest_root: str | Path | None = None,
    action: str = "perform advanced game-file writes",
) -> dict[str, Any]:
    state = runtime_profiles.inspect_runtime_state(
        game_root,
        saved_games_ace_root=saved_games_ace_root,
        package_manifest_root=package_manifest_root,
    )
    if state.get("readyForAdvancedGameWrites") is True:
        return state

    runtime = str(state.get("runtime") or runtime_profiles.RUNTIME_UNKNOWN).strip().lower()
    label = _runtime_label(runtime)
    details = _message_lines(state)
    detail_text = "\n".join(details)
    message = (
        f"Cannot {action} while AC EVO is in {label}. "
        "Advanced LiveryLab game writes require Advanced/extracted mode: "
        "content.kspkg disabled by LiveryLab and loose content/cars available."
    )
    if runtime == runtime_profiles.RUNTIME_MIXED:
        message += " Mixed runtime states must be cleaned up before writing to game files."
    elif runtime == runtime_profiles.RUNTIME_OFFICIAL:
        message += " Switch to the advanced extracted-content workflow before using legacy Activate in Game."
    elif runtime == runtime_profiles.RUNTIME_UNKNOWN:
        message += " LiveryLab could not prove which runtime mode is active."
    if detail_text:
        message = f"{message}\n{detail_text}"
    raise RuntimeError(message)
