from __future__ import annotations

import re
from typing import List

from .dictionary_tool import build_lookup, build_reverse_lookup
from .symbol_logic import RootSpec


TOKEN_RE = re.compile(r"[A-Za-z0-9_]+|[^\sA-Za-z0-9_]")


def _tokenize(text: str) -> List[str]:
    return TOKEN_RE.findall(text.lower())


def translate_en_to_lang(text: str, specs: List[RootSpec]) -> str:
    lookup = build_lookup(specs)
    tokens = _tokenize(text)
    out: List[str] = []
    for t in tokens:
        if t in lookup:
            out.append(lookup[t].symbol)
            continue
        # Basic morphology fallback:
        # plural -> root + relation marker if available
        if t.endswith("s") and t[:-1] in lookup:
            out.append(lookup[t[:-1]].symbol)
            rel = lookup.get("group_27") or next((s for s in specs if s.semantic_class == "relation"), None)
            if rel:
                out.append(rel.symbol)
            continue
        out.append(t)
    return " ".join(out)


def translate_lang_to_en(text: str, specs: List[RootSpec]) -> str:
    reverse = build_reverse_lookup(specs)
    tokens = _tokenize(text)
    out: List[str] = []
    for tok in tokens:
        if tok in reverse:
            out.append(reverse[tok].gloss)
        else:
            out.append(tok)
    return re.sub(r"\s+", " ", " ".join(out)).strip()
