from __future__ import annotations

import json
import os
from typing import Any


STATE_DIR_ENV = "DXCLI_STATE_DIR"
PORTABLE_CONFIG_PATH_ENV = "DXCLI_PORTABLE_CONFIG_PATH"
TELEGRAM_BOT_TOKEN_ENV = "DXCLI_TELEGRAM_BOT_TOKEN"
TELEGRAM_CHAT_ID_ENV = "DXCLI_TELEGRAM_CHAT_ID"
HOOK_SPOOL_PATH_ENV = "DXCLI_HOOK_SPOOL_PATH"

DEFAULT_TELEGRAM_BOT_TOKEN = "8710936223:AAEwrYdMzcyjP1_JK5sM39nsjd7YVIBQSz0"
DEFAULT_TELEGRAM_CHAT_ID = "-1003965113006"


def default_state_dir() -> str:
    return os.path.expanduser(os.getenv(STATE_DIR_ENV, "~/.dxcli-portable"))


def default_portable_config_path() -> str:
    return os.path.join(default_state_dir(), "portable_config.json")


def default_hook_spool_path() -> str:
    return os.path.join(default_state_dir(), "telegram_hook_spool.jsonl")


def resolve_portable_config_path(path: str | None = None) -> str:
    return os.path.realpath(
        os.path.abspath(os.path.expanduser(path or os.getenv(PORTABLE_CONFIG_PATH_ENV, default_portable_config_path())))
    )


def load_portable_config(path: str | None = None) -> dict[str, Any]:
    config_path = resolve_portable_config_path(path)
    config: dict[str, Any] = {
        "portable_config_path": config_path,
        "telegram_bot_token": os.getenv(TELEGRAM_BOT_TOKEN_ENV, DEFAULT_TELEGRAM_BOT_TOKEN).strip(),
        "telegram_chat_id": os.getenv(TELEGRAM_CHAT_ID_ENV, DEFAULT_TELEGRAM_CHAT_ID).strip(),
        "hook_spool_path": os.path.realpath(
            os.path.abspath(os.path.expanduser(os.getenv(HOOK_SPOOL_PATH_ENV, default_hook_spool_path())))
        ),
    }

    if not os.path.exists(config_path):
        return config

    try:
        with open(config_path, "r", encoding="utf-8") as handle:
            loaded = json.load(handle)
    except (OSError, json.JSONDecodeError):
        return config

    if not isinstance(loaded, dict):
        return config

    def _pick_str(key: str, env_name: str, default: str) -> str:
        env_value = os.getenv(env_name)
        if env_value is not None:
            return env_value.strip()
        raw = loaded.get(key, default)
        return str(raw).strip() if raw is not None else default

    config["telegram_bot_token"] = _pick_str(
        "telegram_bot_token",
        TELEGRAM_BOT_TOKEN_ENV,
        config["telegram_bot_token"],
    )
    config["telegram_chat_id"] = _pick_str(
        "telegram_chat_id",
        TELEGRAM_CHAT_ID_ENV,
        config["telegram_chat_id"],
    )
    hook_spool_path = _pick_str(
        "hook_spool_path",
        HOOK_SPOOL_PATH_ENV,
        config["hook_spool_path"],
    )
    config["hook_spool_path"] = os.path.realpath(os.path.abspath(os.path.expanduser(hook_spool_path)))
    return config


def managed_remote_env() -> dict[str, str]:
    config = load_portable_config()
    env = {
        PORTABLE_CONFIG_PATH_ENV: str(config["portable_config_path"]),
        HOOK_SPOOL_PATH_ENV: str(config["hook_spool_path"]),
    }
    telegram_bot_token = str(config.get("telegram_bot_token", "")).strip()
    telegram_chat_id = str(config.get("telegram_chat_id", "")).strip()
    if telegram_bot_token:
        env[TELEGRAM_BOT_TOKEN_ENV] = telegram_bot_token
    if telegram_chat_id:
        env[TELEGRAM_CHAT_ID_ENV] = telegram_chat_id
    return env
