from __future__ import annotations

from copy import deepcopy
from dataclasses import dataclass
import math
from typing import Any, Literal


PreferenceType = Literal["bool", "int", "float", "string"]
PREFERENCE_VERSION = 11
MAX_PREFERENCE_DEPTH = 8
MAX_PREFERENCE_LEAVES = 100
MAX_PREFERENCE_KEY_LENGTH = 80


@dataclass(frozen=True)
class PreferenceSpec:
    default: Any
    value_type: PreferenceType
    options: tuple[Any, ...] = ()
    min_value: float | None = None
    max_value: float | None = None
    max_length: int = 120


PREFERENCE_CATALOG: dict[str, PreferenceSpec] = {
    "interface.appearance.theme": PreferenceSpec(
        "metal",
        "string",
        ("standard", "metal", "graphite", "drawing-board"),
    ),
    "interface.panels.draggable": PreferenceSpec(True, "bool"),
    "viewer.navigation.orbitModifier": PreferenceSpec("shift", "string", ("shift", "ctrl", "alt")),
    "viewer.navigation.panButton": PreferenceSpec("middle", "string", ("middle",)),
    "viewer.navigation.zoomWheel": PreferenceSpec("standard", "string", ("standard", "inverted")),
    "viewer.navigation.doubleMiddleClick": PreferenceSpec("recenter", "string", ("recenter", "none")),
    "viewer.visual.theme": PreferenceSpec("technical-light", "string"),
    "viewer.visual.backgroundMode": PreferenceSpec("white", "string", ("white", "black", "custom")),
    "viewer.visual.backgroundCustom": PreferenceSpec("#ffffff", "string"),
    "viewer.visual.selectedNodeColor": PreferenceSpec("#d8a400", "string"),
    "viewer.visual.selectedElementColor": PreferenceSpec("#d8a400", "string"),
    "viewer.visual.nodeSize": PreferenceSpec(0.055, "float", min_value=0.01, max_value=1.0),
    "viewer.visual.barLineWidth": PreferenceSpec(2, "int", min_value=1, max_value=12),
    "viewer.visual.showCompositeMembers": PreferenceSpec(True, "bool"),
    "viewer.visual.showGrid": PreferenceSpec(False, "bool"),
    "viewer.visual.gridSize": PreferenceSpec(30, "int", min_value=1, max_value=500),
    "viewer.visual.axesSize": PreferenceSpec(3, "int", min_value=0, max_value=100),
    "viewer.loads.show": PreferenceSpec(False, "bool"),
    "viewer.loads.arrowScale": PreferenceSpec(1.0, "float", min_value=0.1, max_value=10.0),
    "viewer.loads.showLabels": PreferenceSpec(False, "bool"),
    "viewer.hover.enabled": PreferenceSpec(True, "bool"),
    "viewer.hover.minPixelsPerModelUnit": PreferenceSpec(18, "float", min_value=0, max_value=1000),
    "viewer.hover.barPixelRadius": PreferenceSpec(7, "float", min_value=1, max_value=40),
    "viewer.hover.loadPixelRadius": PreferenceSpec(4, "float", min_value=1, max_value=40),
    "viewer.results.diagramPoints": PreferenceSpec(21, "int", min_value=2, max_value=401),
    "modeling.coordinateInput": PreferenceSpec(False, "bool"),
    "modeling.objectSnap": PreferenceSpec(True, "bool"),
    "modeling.objectSnapRadiusPx": PreferenceSpec(14, "float", min_value=2, max_value=80),
    "modeling.objectSnapReleaseMultiplier": PreferenceSpec(2.15, "float", min_value=1, max_value=4),
    "modeling.workPlaneAxis": PreferenceSpec("xy", "string", ("xy", "xz", "yz")),
    "modeling.workPlaneOffset": PreferenceSpec(0, "float", min_value=-1000000, max_value=1000000),
    "shortcuts.solve": PreferenceSpec("Ctrl+Enter", "string"),
    "shortcuts.undo": PreferenceSpec("Ctrl+Z", "string"),
    "shortcuts.redo": PreferenceSpec("Ctrl+Y", "string"),
    "shortcuts.loadDemo": PreferenceSpec("Ctrl+D", "string"),
    "shortcuts.addNode": PreferenceSpec("N", "string"),
    "shortcuts.addBar": PreferenceSpec("B", "string"),
    "shortcuts.moveSelection": PreferenceSpec("M", "string"),
    "shortcuts.copySelection": PreferenceSpec("Ctrl+C", "string"),
    "shortcuts.measureDistance": PreferenceSpec("Alt+D", "string"),
    "shortcuts.layerManager": PreferenceSpec("Alt+L", "string"),
    "shortcuts.commandPalette": PreferenceSpec("Alt+K", "string"),
    "shortcuts.deleteSelection": PreferenceSpec("Delete", "string"),
    "shortcuts.deleteSelectionSecondary": PreferenceSpec("E", "string"),
    "shortcuts.orbitMode": PreferenceSpec("V", "string"),
    "shortcuts.toggleSidebar": PreferenceSpec("Alt+F", "string"),
    "shortcuts.toggleResults": PreferenceSpec("Alt+R", "string"),
    "shortcuts.cycleBackground": PreferenceSpec("Alt+B", "string"),
    "shortcuts.toggleLoads": PreferenceSpec("Alt+C", "string"),
    "shortcuts.toggleGrid": PreferenceSpec("", "string"),
    "shortcuts.toggleTopMenu": PreferenceSpec("", "string"),
    "layout.sidebar.defaultOpen": PreferenceSpec(False, "bool"),
    "layout.results.defaultOpen": PreferenceSpec(False, "bool"),
    "layout.topMenu.interaction": PreferenceSpec("click", "string", ("hover", "click")),
    "projects.autosaveDelaySeconds": PreferenceSpec(300, "int", min_value=60, max_value=1800),
    "icons.pack": PreferenceSpec("technical-default", "string"),
    "icons.style": PreferenceSpec("line", "string", ("line", "filled", "duotone")),
    # O pipeline de entrada, calculo e resultados usa SI. Outras unidades so
    # devem voltar ao catalogo quando houver conversao completa ponta a ponta.
    "units.force": PreferenceSpec("N", "string", ("N",)),
    "units.length": PreferenceSpec("m", "string", ("m",)),
    "units.moment": PreferenceSpec("N.m", "string", ("N.m",)),
    "solver.defaultEngine": PreferenceSpec("openseespy", "string", ("auto", "openseespy")),
}


def preference_catalog_response() -> dict[str, dict[str, Any]]:
    return {
        key: {
            "default": spec.default,
            "type": spec.value_type,
            "options": list(spec.options),
            "min": spec.min_value,
            "max": spec.max_value,
        }
        for key, spec in PREFERENCE_CATALOG.items()
    }


def default_preferences() -> dict[str, Any]:
    values: dict[str, Any] = {}
    for path, spec in PREFERENCE_CATALOG.items():
        _set_path(values, path.split("."), deepcopy(spec.default))
    return values


def merge_preferences(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
    merged = deepcopy(base)
    _deep_merge_in_place(merged, override)
    return merged


def sanitize_preference_overrides(overrides: dict[str, Any]) -> dict[str, Any]:
    """Discard persisted values that no longer satisfy the active catalog."""
    sanitized: dict[str, Any] = {}
    try:
        flattened = _flatten_dict(overrides)
    except ValueError:
        return sanitized
    for path, value in flattened.items():
        spec = PREFERENCE_CATALOG.get(path)
        if spec is None:
            continue
        try:
            _validate_value(path, value, spec)
        except ValueError:
            continue
        _set_path(sanitized, path.split("."), deepcopy(value))
    return sanitized


def validate_preference_patch(patch: dict[str, Any]) -> None:
    flat = _flatten_dict(patch)
    if not flat:
        raise ValueError("Envie ao menos uma preferencia para alterar.")

    for path, value in flat.items():
        spec = PREFERENCE_CATALOG.get(path)
        if spec is None:
            raise ValueError(f"Preferencia desconhecida: {path}")
        _validate_value(path, value, spec)


def preference_namespaces(patch: dict[str, Any]) -> set[str]:
    return {key for key, value in patch.items() if isinstance(value, dict)}


def _validate_value(path: str, value: Any, spec: PreferenceSpec) -> None:
    if spec.value_type == "bool" and type(value) is not bool:
        raise ValueError(f"Preferencia {path} deve ser booleana.")
    if spec.value_type == "int" and (type(value) is not int):
        raise ValueError(f"Preferencia {path} deve ser inteira.")
    if spec.value_type == "float" and (type(value) not in (int, float)):
        raise ValueError(f"Preferencia {path} deve ser numerica.")
    if spec.value_type == "string" and type(value) is not str:
        raise ValueError(f"Preferencia {path} deve ser texto.")
    if spec.value_type == "string" and len(value) > spec.max_length:
        raise ValueError(f"Preferencia {path} deve ter no maximo {spec.max_length} caracteres.")

    if isinstance(value, float) and not math.isfinite(value):
        raise ValueError(f"Preferencia {path} deve ser finita.")

    if spec.options and value not in spec.options:
        allowed = ", ".join(str(item) for item in spec.options)
        raise ValueError(f"Preferencia {path} deve ser uma destas opcoes: {allowed}.")

    if isinstance(value, (int, float)):
        if spec.min_value is not None and value < spec.min_value:
            raise ValueError(f"Preferencia {path} deve ser >= {spec.min_value}.")
        if spec.max_value is not None and value > spec.max_value:
            raise ValueError(f"Preferencia {path} deve ser <= {spec.max_value}.")


def _set_path(values: dict[str, Any], path: list[str], value: Any) -> None:
    current = values
    for item in path[:-1]:
        current = current.setdefault(item, {})
    current[path[-1]] = value


def _flatten_dict(values: dict[str, Any], prefix: str = "") -> dict[str, Any]:
    flat: dict[str, Any] = {}
    stack: list[tuple[str, dict[str, Any], int]] = [(prefix, values, 0)]
    while stack:
        current_prefix, current_values, depth = stack.pop()
        if depth > MAX_PREFERENCE_DEPTH:
            raise ValueError("Preferencias excedem a profundidade permitida.")
        for key, value in current_values.items():
            if not isinstance(key, str) or not key or len(key) > MAX_PREFERENCE_KEY_LENGTH:
                raise ValueError("Chave de preferencia invalida.")
            path = f"{current_prefix}.{key}" if current_prefix else key
            if isinstance(value, dict):
                if not value:
                    raise ValueError(f"Namespace de preferencias vazio: {path}")
                stack.append((path, value, depth + 1))
                continue
            flat[path] = value
            if len(flat) > MAX_PREFERENCE_LEAVES:
                raise ValueError("Preferencias excedem a quantidade permitida.")
    return flat


def _deep_merge_in_place(target: dict[str, Any], override: dict[str, Any]) -> None:
    for key, value in override.items():
        if isinstance(value, dict) and isinstance(target.get(key), dict):
            _deep_merge_in_place(target[key], value)
        else:
            target[key] = deepcopy(value)
