"""Lightweight runtime internationalization."""

from __future__ import annotations

import locale
import os


TRANSLATIONS: dict[str, dict[str, str]] = {
    "en": {
        "cli.description": "Memnixa CLI, gateway, config, and data tools",
        "cli.help.agent": "Run the agent locally or via gateway",
        "cli.help.chat": "Backward-compatible alias of agent",
        "cli.help.gateway": "Run the gateway server",
        "cli.help.config": "Manage the user-level Memnixa config in ~/.memnixa",
        "cli.help.data": "Inspect the SQLite-backed stored sessions and messages",
        "cli.help.identity": "Manage canonical users and external identity bindings",
        "cli.help.identity.bind_owner": "Bind one channel identity to the local owner",
        "cli.help.identity.list": "Print canonical users and bound external identities",
        "cli.help.identity.channel": "Channel name, for example qq or feishu",
        "cli.help.identity.external_id": "Channel-specific sender id such as open_id",
        "cli.help.config.sync": (
            "Create or incrementally update ~/.memnixa/config.json from the example template"
        ),
        "cli.help.config.path": "Print the default user-level config path",
        "cli.help.config.open": "Open the default config file with the system default application",
        "cli.help.config.add_model": "Add one provider/model profile into the config file",
        "cli.help.config.add_model.provider": "Built-in provider preset name",
        "cli.help.config.add_model.id": "Optional provider id override used by /use <id>",
        "cli.help.config.add_model.label": "Optional display label override",
        "cli.help.config.add_model.api_key": "Provider API key",
        "cli.help.config.add_model.model": "Provider model id",
        "cli.help.config.add_model.api_base": "Override API base URL",
        "cli.help.config.add_model.set_default": "Set the newly added provider as default",
        "cli.help.config.path_flag": "Print the target config path after syncing",
        "cli.help.data.dump": "Print stored sessions and messages from the SQLite database",
        "cli.help.data.session_id": "Optional session id filter",
        "cli.help.data.limit": "Limit the number of returned messages",
        "cli.help.config_path": "Path to a JSON config file. Default lookup: ./config.json, then {path}",
        "cli.help.message": "Send one message and exit",
        "cli.help.via": "Choose how the CLI reaches the agent runtime.",
        "cli.help.gateway_url": "Gateway base URL, e.g. http://127.0.0.1:8787",
        "cli.help.gateway_host": "Gateway host override",
        "cli.help.gateway_port": "Gateway port override",
        "cli.help.gateway_config": "Path to a JSON config file",
        "config.sync.created": "Memnixa config created: {path}",
        "config.sync.updated": "Memnixa config updated: {path}",
        "config.sync.added_fields": "Added missing fields:",
        "config.sync.no_changes": "No missing fields were added.",
        "config.sync.home": "Memnixa home: {path}",
        "config.opened": "Opened {path}",
        "config.add_model.supported": "Supported provider presets:",
        "config.add_model.supported_item": (
            "  {index}. {label} ({preset}) "
            "[api_base={api_base}, model={model}]"
        ),
        "config.add_model.prompt.provider": "Choose provider preset",
        "config.add_model.prompt.id": "Provider id",
        "config.add_model.prompt.label": "Display label",
        "config.add_model.prompt.api_key": "API key",
        "config.add_model.prompt.model": "Model id",
        "config.add_model.prompt.api_base": "API base URL",
        "config.add_model.prompt.set_default": "Set this provider as default?",
        "config.add_model.invalid_provider": "Unknown provider preset: {value}",
        "config.add_model.invalid_yes_no": "Please answer yes or no.",
        "config.add_model.required": "{field} is required.",
        "config.add_model.non_interactive": (
            "missing required interactive field: {field}. "
            "Pass it explicitly with command flags."
        ),
        "config.add_model.saved": "Saved provider config to {path}",
        "config.add_model.summary": (
            "Added provider {id}: {label} "
            "[preset={preset}, model={model}]"
        ),
        "config.add_model.default": "Current default provider: {id} / {label}",
        "config.add_model.providers": "Configured providers:",
        "config.add_model.provider_item": (
            "  - {id}. {label} [preset={preset}, model={model}]"
        ),
        "identity.bind_owner.saved": (
            "Bound {channel}:{external_id} to owner user {user_id}"
        ),
        "gateway.listening": "Memnixa gateway listening on http://{host}:{port}",
        "ui.title": "terminal agent",
        "ui.session": "Session",
        "ui.mode": "mode={value}",
        "ui.provider": "provider={id} {label}",
        "ui.provider_gateway": "provider=(gateway-only)",
        "ui.model": "model={value}",
        "ui.gateway": "gateway={value}",
        "ui.welcome": "Enter submit, Esc+Enter newline, Ctrl+L clear screen",
        "ui.model_help": "/use <id> switch model, /models list models, /runtime show runtime, /whoami show identity",
        "ui.prompt.input": "Message",
        "ui.user": "User",
        "ui.assistant": "Memnixa",
        "ui.busy.local": "Memnixa is thinking and using tools",
        "ui.busy.gateway": "Memnixa is waiting for the gateway response",
        "ui.input_cancelled": "Input cancelled",
        "ui.fallback": "gateway unavailable, fell back to local mode: {error}",
        "ui.exit_hint": "• exit quit/exit ",
        "ui.exit_hint_short": "quit/exit",
        "ui.toolbar": " via {via} • provider {provider_id}:{provider_label} • model {model} • gateway {gateway} ",
        "agent.models.title": "Available models:",
        "agent.models.switch_hint": "Use `/use <id>` to switch the current session model.",
        "agent.runtime.title": "Current runtime:",
        "agent.identity.title": "Current identity:",
        "agent.identity.status": "identity_status: {value}",
        "agent.identity.role": "actor_role: {value}",
        "agent.identity.user_id": "actor_user_id: {value}",
        "agent.identity.external_id": "actor_external_id: {value}",
        "agent.identity.is_owner": "actor_is_owner: {value}",
        "agent.identity.channel": "channel: {value}",
        "agent.identity.session": "session_id: {value}",
        "agent.use.switched": "Switched to model {id}: {label} / {model}",
        "agent.provider.unknown": "unknown provider id '{provider_id}', expected one of: {available}",
        "agent.local_requires_config": "local mode requires a config with provider credentials",
        "agent.gateway_requires_url": "gateway mode requires --gateway-url or gateway config",
        "agent.auto_no_fallback": "gateway call failed and no local config is available for fallback: {error}",
        "reply.mode": "mode={value}",
        "reply.iter": "iter={value}",
        "reply.tools": "tools={value}",
        "reply.provider": "provider={value}",
        "reply.model": "model={value}",
        "reply.run": "run={value}",
    },
    "zh-CN": {
        "cli.description": "Memnixa 命令行、网关、配置与数据工具",
        "cli.help.agent": "本地或通过 gateway 运行智能体",
        "cli.help.chat": "兼容旧用法的 agent 别名",
        "cli.help.gateway": "启动 gateway 服务",
        "cli.help.config": "管理位于 ~/.memnixa 的用户级 Memnixa 配置",
        "cli.help.data": "查看使用 SQLite 持久化的会话与消息数据",
        "cli.help.identity": "管理规范用户与外部身份绑定",
        "cli.help.identity.bind_owner": "将一个渠道身份绑定到本地主人",
        "cli.help.identity.list": "输出规范用户与已绑定的外部身份",
        "cli.help.identity.channel": "渠道名，例如 qq 或 feishu",
        "cli.help.identity.external_id": "渠道侧发送者 ID，例如 open_id",
        "cli.help.config.sync": "根据示例模板创建或增量更新 ~/.memnixa/config.json",
        "cli.help.config.path": "输出默认用户级配置文件路径",
        "cli.help.config.open": "用系统默认程序打开配置文件",
        "cli.help.config.add_model": "向配置文件中新增一个 provider/model 配置",
        "cli.help.config.add_model.provider": "内置 provider 预设名",
        "cli.help.config.add_model.id": "可选，覆盖自动生成的 provider id（用于 /use <id>）",
        "cli.help.config.add_model.label": "可选，覆盖默认显示名称",
        "cli.help.config.add_model.api_key": "Provider API Key",
        "cli.help.config.add_model.model": "模型 ID",
        "cli.help.config.add_model.api_base": "覆盖 API 基础地址",
        "cli.help.config.add_model.set_default": "将新加的 provider 设为默认值",
        "cli.help.config.path_flag": "同步后额外输出目标配置路径",
        "cli.help.data.dump": "输出 SQLite 数据库中的会话与消息",
        "cli.help.data.session_id": "可选的 session_id 过滤条件",
        "cli.help.data.limit": "限制返回的消息数量",
        "cli.help.config_path": "JSON 配置文件路径。默认查找顺序：./config.json，然后 {path}",
        "cli.help.message": "发送一条消息后退出",
        "cli.help.via": "选择 CLI 如何连接到智能体运行时。",
        "cli.help.gateway_url": "Gateway 基础地址，例如 http://127.0.0.1:8787",
        "cli.help.gateway_host": "覆盖 gateway 主机地址",
        "cli.help.gateway_port": "覆盖 gateway 端口",
        "cli.help.gateway_config": "JSON 配置文件路径",
        "config.sync.created": "已创建 Memnixa 配置：{path}",
        "config.sync.updated": "已更新 Memnixa 配置：{path}",
        "config.sync.added_fields": "新增缺失字段：",
        "config.sync.no_changes": "没有新增任何缺失字段。",
        "config.sync.home": "Memnixa 主目录：{path}",
        "config.opened": "已打开 {path}",
        "config.add_model.supported": "系统支持的 provider 预设：",
        "config.add_model.supported_item": (
            "  {index}. {label} ({preset}) "
            "[api_base={api_base}, model={model}]"
        ),
        "config.add_model.prompt.provider": "选择 provider 预设",
        "config.add_model.prompt.id": "Provider 编号",
        "config.add_model.prompt.label": "显示名称",
        "config.add_model.prompt.api_key": "API Key",
        "config.add_model.prompt.model": "模型 ID",
        "config.add_model.prompt.api_base": "API 基础地址",
        "config.add_model.prompt.set_default": "是否将该 provider 设为默认值？",
        "config.add_model.invalid_provider": "未知 provider 预设：{value}",
        "config.add_model.invalid_yes_no": "请输入 yes/no。",
        "config.add_model.required": "{field} 不能为空。",
        "config.add_model.non_interactive": (
            "缺少必填交互字段：{field}。"
            "请通过命令参数显式传入。"
        ),
        "config.add_model.saved": "已将 provider 配置写入 {path}",
        "config.add_model.summary": (
            "已新增 provider {id}：{label} "
            "[preset={preset}, model={model}]"
        ),
        "config.add_model.default": "当前默认 provider：{id} / {label}",
        "config.add_model.providers": "当前 provider 列表：",
        "config.add_model.provider_item": (
            "  - {id}. {label} [preset={preset}, model={model}]"
        ),
        "identity.bind_owner.saved": (
            "已将 {channel}:{external_id} 绑定到主人用户 {user_id}"
        ),
        "gateway.listening": "Memnixa gateway 正在监听 http://{host}:{port}",
        "ui.title": "终端智能体",
        "ui.session": "会话",
        "ui.mode": "模式={value}",
        "ui.provider": "模型源={id} {label}",
        "ui.provider_gateway": "模型源=(仅 gateway)",
        "ui.model": "模型={value}",
        "ui.gateway": "gateway={value}",
        "ui.welcome": "Enter 提交，Esc+Enter 换行，Ctrl+L 清屏",
        "ui.model_help": "/use <id> 切换模型，/models 查看模型列表，/runtime 查看运行环境，/whoami 查看身份",
        "ui.prompt.input": "输入消息",
        "ui.user": "主人",
        "ui.assistant": "Memnixa",
        "ui.busy.local": "Memnixa 正在思考与调用工具",
        "ui.busy.gateway": "Memnixa 正在等待 gateway 返回",
        "ui.input_cancelled": "输入已取消",
        "ui.fallback": "gateway 不可用，已回退本地执行：{error}",
        "ui.exit_hint": "• exit quit/exit ",
        "ui.exit_hint_short": "quit/exit",
        "ui.toolbar": " via {via} • 模型源 {provider_id}:{provider_label} • 模型 {model} • gateway {gateway} ",
        "agent.models.title": "可用模型列表：",
        "agent.models.switch_hint": "使用 `/use <id>` 可切换当前会话的模型。",
        "agent.runtime.title": "当前运行环境：",
        "agent.identity.title": "当前身份：",
        "agent.identity.status": "identity_status: {value}",
        "agent.identity.role": "actor_role: {value}",
        "agent.identity.user_id": "actor_user_id: {value}",
        "agent.identity.external_id": "actor_external_id: {value}",
        "agent.identity.is_owner": "actor_is_owner: {value}",
        "agent.identity.channel": "channel: {value}",
        "agent.identity.session": "session_id: {value}",
        "agent.use.switched": "已切换到模型 {id}：{label} / {model}",
        "agent.provider.unknown": "未知模型编号 '{provider_id}'，可选值有：{available}",
        "agent.local_requires_config": "本地模式需要带有模型凭据的配置",
        "agent.gateway_requires_url": "gateway 模式需要 --gateway-url 或配置中的 gateway 地址",
        "agent.auto_no_fallback": "gateway 调用失败，且没有可回退的本地配置：{error}",
        "reply.mode": "mode={value}",
        "reply.iter": "iter={value}",
        "reply.tools": "tools={value}",
        "reply.provider": "provider={value}",
        "reply.model": "model={value}",
        "reply.run": "run={value}",
    },
}


def get_language() -> str:
    """Resolve the runtime UI language."""
    override = os.getenv("MEMNIXA_LANG")
    if override:
        return _normalize(override)

    for key in ("LC_ALL", "LC_MESSAGES", "LANG"):
        value = os.getenv(key)
        if value:
            return _normalize(value)

    current = locale.getlocale()[0] or locale.getdefaultlocale()[0] or ""
    return _normalize(current)


def _normalize(raw: str) -> str:
    lowered = raw.replace("_", "-").lower()
    if lowered.startswith("zh"):
        return "zh-CN"
    return "en"


def t(key: str, **kwargs: object) -> str:
    """Translate one runtime key."""
    language = get_language()
    template = TRANSLATIONS.get(language, TRANSLATIONS["en"]).get(
        key,
        TRANSLATIONS["en"].get(key, key),
    )
    return template.format(**kwargs)
