"""Shared utilities for Condensa encoder/decoder (v0.3)."""
# v0.3 changes: !! -> !?, // removed, ' -> /each

import tiktoken

_enc = None


def get_encoder():
    """Get shared tiktoken encoder instance."""
    global _enc
    if _enc is None:
        _enc = tiktoken.get_encoding("cl100k_base")
    return _enc


def count_tokens(text: str) -> int:
    """Count tokens using cl100k_base encoding."""
    return len(get_encoder().encode(text))


def tokenize(text: str) -> list[str]:
    """Return list of token strings."""
    enc = get_encoder()
    token_ids = enc.encode(text)
    return [enc.decode([t]) for t in token_ids]


# ─── Condensa Vocabulary (v0.3) ────────────────────────────────────

MSG_TYPES = {
    "command": "!",
    "sync_command": "!?",
    "query": "?",
    "result": "=",
    "delegate": ">",
    "receive": "<",
    "update": "~",
    "status": "#",
    "cancel": "X",
    "error": "E",
    "meta": "@",
}

# Reverse map — !? must be checked before ! in parsing
MSG_TYPES_REV = {}
for k, v in MSG_TYPES.items():
    MSG_TYPES_REV[v] = k
# Backward compat: old !! syntax still decodes to sync_command
MSG_TYPES_REV["!!"] = "sync_command"

ACTIONS = {
    "search": "srch",
    "filter": "filt",
    "sort": "sort",
    "group_by": "grp",
    "group": "grp",
    "aggregate": "agg",
    "count": "cnt",
    "average": "avg",
    "mean": "avg",
    "sum": "sum",
    "transform": "xfm",
    "merge": "mrg",
    "split": "splt",
    "deduplicate": "dedup",
    "generate": "gen",
    "summarize": "sumz",
    "summary": "sumz",
    "translate": "xlat",
    "format": "fmt",
    "validate": "val",
    "compare": "cmp",
    "classify": "cls",
    "extract": "ext",
    "enrich": "enr",
    "rank": "rank",
    "api_call": "call",
    "call": "call",
    "read": "read",
    "fetch": "read",
    "write": "wrt",
    "store": "wrt",
    "delete": "del",
    "remove": "del",
    "execute": "exec",
    "run": "exec",
    "wait": "wait",
    "retry": "retry",
    "log": "log",
    "sequential": "seq",
    "parallel": "par",
    "conditional": "if",
    "iterate": "loop",
    "pipeline": "pipe",
    "ocr": "ocr",
    "describe": "desc",
    "identify": "ident",
    "check": "chk",
    "analyze": "anlz",
    "process": "proc",
    "upload": "upl",
    "download": "dl",
    "send": "snd",
    "receive": "rcv",
    "cluster": "cls",
    "recommend": "rec",
    "score": "scr",
    "review": "review",
    "assign": "asgn",
    "create": "crt",
    "deploy": "deploy",
    "test": "test",
    "build": "build",
    "scan": "scan",
    "inspect": "insp",
    "monitor": "mon",
    "alert": "alert",
    "notify": "ntfy",
    "approve": "aprv",
    "reject": "rjct",
    "schedule": "sched",
    "backup": "bkup",
    # Code architecture (Condensa Code)
    "define": "def",
    "function": "fn",
    "component": "fn",
    "type": "type",
    "interface": "type",
    "wire": "wire",
    "connect": "wire",
    "endpoint": "api",
    "schema": "schema",
    "table": "schema",
    "modify": "mod",
    "assemble": "asm",
}

ACTIONS_REV = {}
for k, v in ACTIONS.items():
    if v not in ACTIONS_REV:
        ACTIONS_REV[v] = k

# Condensa Code: override reverse mappings with readable names
ACTIONS_REV["def"] = "define_module"
ACTIONS_REV["fn"] = "define_function"
ACTIONS_REV["type"] = "define_type"
ACTIONS_REV["wire"] = "wire"
ACTIONS_REV["api"] = "api_endpoint"
ACTIONS_REV["schema"] = "define_schema"
ACTIONS_REV["mod"] = "modify"
ACTIONS_REV["asm"] = "assemble"

# Set of known action short codes for bare-verb pipeline parsing
KNOWN_ACTIONS = set(ACTIONS.values())

URGENCY = {
    "critical": "+++",
    "high": "++",
    "normal": "+",
    "low": "-",
    "background": "--",
}

URGENCY_REV = {v: k for k, v in URGENCY.items()}

CONFIDENCE = {
    "certain": "!",
    "verified": "!!",
    "likely": "~",
    "uncertain": "~~",
    "guess": "???",
}

CONFIDENCE_REV = {v: k for k, v in CONFIDENCE.items()}

FALLBACKS = {
    "cache": "fb:cache",
    "cached_data": "fb:cache",
    "skip": "fb:skip",
    "abort": "fb:abort",
    "default": "fb:default",
    "ask": "fb:ask",
    "degrade": "fb:degrade",
    "partial": "fb:degrade",
}

ERROR_CODES = {
    "timeout": "timeout",
    "authentication": "auth",
    "not_found": "404",
    "rate_limit": "429",
    "rate_limited": "429",
    "server_error": "5xx",
    "service_unavailable": "503",
    "parse_error": "parse",
    "type_error": "type",
    "overflow": "overflow",
    "partial_failure": "partial",
}

FORMAT_MAP = {
    "bullet_points": "bullets",
    "bullets": "bullets",
    "markdown": "md",
    "json": "json",
    "csv": "csv",
    "table": "table",
    "plain": "plain",
    "xml": "xml",
}

# ─── v0.3 Additions ───────────────────────────────────────────────

IMPLICIT_VARS = {
    "$_": "last_result",
    "$turn": "turn_number",
    "$agent": "current_agent",
    "$t": "timestamp",
}

IMPLICIT_VARS_REV = {v: k for k, v in IMPLICIT_VARS.items()}

POLICY_FIELDS = {"retry", "timeout", "fb", "backoff"}
