"""Expression evaluation over render data (TZ 2.3.7, 2.4)."""

from __future__ import annotations

from collections.abc import Mapping
from dataclasses import dataclass, field
from decimal import Decimal, DivisionByZero, InvalidOperation
from typing import Any

from ..errors import Warnings
from ..fmt import format_date, format_plain_number, locale_table, to_decimal
from .parser import Ast, TemplatePart


class _Missing:
    __slots__ = ()

    def __repr__(self) -> str:
        return "MISSING"

    def __bool__(self) -> bool:
        return False


MISSING: Any = _Missing()


class Scope:
    """Lookup chain: innermost variables first (repeater item, loop, page), then the root data."""

    __slots__ = ("parent", "vars")

    def __init__(self, vars: Mapping[str, Any], parent: Scope | None = None) -> None:
        self.vars = vars
        self.parent = parent

    def child(self, vars: Mapping[str, Any]) -> Scope:
        return Scope(vars, self)

    def lookup(self, name: str) -> Any:
        scope: Scope | None = self
        while scope is not None:
            if name in scope.vars:
                return scope.vars[name]
            scope = scope.parent
        return MISSING


@dataclass
class EvalEnv:
    locale: str = "ru"
    warnings: Warnings = field(default_factory=Warnings)
    node_id: str | None = None
    missing_placeholder: bool = False
    tz_offset_minutes: int | None = None


def resolve_path(scope: Scope, segments: tuple[Any, ...]) -> Any:
    value = scope.lookup(segments[0]) if isinstance(segments[0], str) else MISSING
    for seg in segments[1:]:
        if value is MISSING or value is None:
            return MISSING
        if isinstance(seg, int):
            if isinstance(value, list) and -len(value) <= seg < len(value):
                value = value[seg]
            else:
                return MISSING
        elif isinstance(value, Mapping):
            value = value.get(seg, MISSING)
        elif isinstance(value, list) and seg == "length":
            value = len(value)
        else:
            return MISSING
    return value


def truthy(value: Any) -> bool:
    if value is MISSING or value is None:
        return False
    if isinstance(value, Decimal):
        return value != 0
    return bool(value)


def _num(value: Any) -> Decimal | None:
    return to_decimal(value)


def _compare(op: str, a: Any, b: Any) -> bool:
    if op in ("==", "!="):
        da, db = _num(a), _num(b)
        if da is not None and db is not None and not isinstance(a, str) and not isinstance(b, str):
            eq = da == db
        else:
            eq = (None if a is MISSING else a) == (None if b is MISSING else b)
        return eq if op == "==" else not eq
    if op == "in":
        if isinstance(b, str) and isinstance(a, str):
            return a in b
        if isinstance(b, list):
            return any(_compare("==", a, item) for item in b)
        if isinstance(b, Mapping):
            return a in b
        return False
    da, db = _num(a), _num(b)
    if da is None or db is None:
        if isinstance(a, str) and isinstance(b, str):
            da_s, db_s = a, b
            return {"<": da_s < db_s, "<=": da_s <= db_s, ">": da_s > db_s, ">=": da_s >= db_s}[op]
        return False
    return {"<": da < db, "<=": da <= db, ">": da > db, ">=": da >= db}[op]


def _arith(op: str, a: Any, b: Any) -> Any:
    if op == "+" and (isinstance(a, str) or isinstance(b, str)):
        return to_text(a, "en") + to_text(b, "en")
    da, db = _num(a), _num(b)
    if da is None or db is None:
        return MISSING
    try:
        if op == "+":
            return da + db
        if op == "-":
            return da - db
        if op == "*":
            return da * db
        if op == "/":
            return da / db
        if op == "%":
            return da % db
    except (DivisionByZero, InvalidOperation, ZeroDivisionError):
        return MISSING
    return MISSING


def evaluate(ast: Ast, scope: Scope, env: EvalEnv) -> Any:
    kind = ast[0]
    if kind == "path":
        value = resolve_path(scope, ast[1])
        if value is MISSING:
            env.warnings.add("VAR_MISSING", path=_path_text(ast[1]), node=env.node_id)
        return value
    if kind == "num":
        return Decimal(ast[1])
    if kind == "str" or kind == "const":
        return ast[1]
    if kind == "list":
        return [evaluate(item, scope, env) for item in ast[1]]
    if kind == "index":
        return _index(evaluate(ast[1], scope, env), evaluate(ast[2], scope, env))
    if kind == "un":
        v = evaluate(ast[2], scope, env)
        if ast[1] == "!":
            return not truthy(v)
        d = _num(v)
        return -d if d is not None else MISSING
    if kind == "and":
        left = evaluate(ast[1], scope, env)
        return evaluate(ast[2], scope, env) if truthy(left) else left
    if kind == "or":
        left = evaluate(ast[1], scope, env)
        return left if truthy(left) else evaluate(ast[2], scope, env)
    if kind == "cond":
        return evaluate(ast[2] if truthy(evaluate(ast[1], scope, env)) else ast[3], scope, env)
    if kind == "bin":
        op = ast[1]
        a = evaluate(ast[2], scope, env)
        b = evaluate(ast[3], scope, env)
        if op in ("==", "!=", "<", "<=", ">", ">=", "in"):
            return _compare(op, a, b)
        return _arith(op, a, b)
    if kind == "filter":
        from .filters import apply_filter

        name = ast[1]
        # ``default`` must see a missing value without emitting VAR_MISSING.
        value = _quiet_eval(ast[2], scope, env) if name == "default" else evaluate(ast[2], scope, env)
        args = [evaluate(a, scope, env) for a in ast[3]]
        return apply_filter(name, value, args, env)
    raise ValueError(f"Unknown AST node {kind!r}")


def _index(base: Any, key: Any) -> Any:
    if isinstance(base, Mapping):
        return base.get(key, MISSING) if isinstance(key, str) else MISSING
    if isinstance(base, list):
        d = _num(key)
        if d is None:
            return MISSING
        i = int(d)
        return base[i] if -len(base) <= i < len(base) else MISSING
    return MISSING


def _quiet_eval(ast: Ast, scope: Scope, env: EvalEnv) -> Any:
    if ast[0] == "path":
        return resolve_path(scope, ast[1])
    return evaluate(ast, scope, env)


def _path_text(segments: tuple[Any, ...]) -> str:
    out = ""
    for seg in segments:
        if isinstance(seg, int):
            out += f"[{seg}]"
        else:
            out += ("." if out else "") + seg
    return out


def to_text(value: Any, locale: str) -> str:
    """Default conversion of a value to display text."""
    if value is MISSING or value is None:
        return ""
    if isinstance(value, bool):
        return locale_table(locale)["bool"]["true" if value else "false"]
    if isinstance(value, (Decimal, int, float)):
        d = to_decimal(value)
        return format_plain_number(d, locale) if d is not None else str(value)
    if isinstance(value, str):
        return value
    if isinstance(value, list):
        return ", ".join(to_text(v, locale) for v in value)
    if hasattr(value, "year") and hasattr(value, "month"):
        return format_date(value, locale)
    return str(value)


def render_template(parts: tuple[TemplatePart, ...], scope: Scope, env: EvalEnv) -> str:
    out: list[str] = []
    for part in parts:
        if isinstance(part, str):
            out.append(part)
            continue
        _, ast, source = part
        value = evaluate(ast, scope, env)
        if (value is MISSING or value is None) and env.missing_placeholder:
            out.append(f"[{source}]")
        else:
            out.append(to_text(value, env.locale))
    return "".join(out)


def to_float(value: Any, default: float | None = None) -> float | None:
    d = to_decimal(value)
    return float(d) if d is not None else default
