from __future__ import annotations

from pathlib import Path

from ..shared.secrets import get_env_path


BLOCKBEATS_API_KEY_ENV = "BLOCKBEATS_API_KEY"


def read_blockbeats_api_key_from_state_env() -> str | None:
    """
    Read BLOCKBEATS_API_KEY from the shared OpenClaw state `.env`.
    Returns None if missing/empty.
    """

    env_path = get_env_path()
    if not env_path.exists():
        return None
    try:
        content = env_path.read_text(encoding="utf-8")
    except Exception:
        return None

    for raw_line in content.splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue
        if not line.startswith(f"{BLOCKBEATS_API_KEY_ENV}="):
            continue
        val = line.split("=", 1)[1].strip()
        return val or None
    return None


def write_blockbeats_api_key_to_state_env(api_key: str) -> Path:
    """
    Update ONLY the BLOCKBEATS_API_KEY line in the shared state `.env`.
    - If exists: replace that line
    - If not: append
    Keeps all other lines unchanged.
    """

    key = str(api_key or "").strip()
    if not key:
        raise ValueError("api_key is empty")

    env_path = get_env_path()
    env_path.parent.mkdir(parents=True, exist_ok=True)
    if not env_path.exists():
        env_path.write_text("", encoding="utf-8")

    content = env_path.read_text(encoding="utf-8")
    lines = content.splitlines()
    out: list[str] = []
    replaced = False
    for raw_line in lines:
        if raw_line.strip().startswith(f"{BLOCKBEATS_API_KEY_ENV}="):
            out.append(f"{BLOCKBEATS_API_KEY_ENV}={key}")
            replaced = True
        else:
            out.append(raw_line)
    if not replaced:
        if out and out[-1].strip() != "":
            out.append("")
        out.append(f"{BLOCKBEATS_API_KEY_ENV}={key}")

    env_path.write_text("\n".join(out) + "\n", encoding="utf-8")
    return env_path


__all__ = [
    "BLOCKBEATS_API_KEY_ENV",
    "read_blockbeats_api_key_from_state_env",
    "write_blockbeats_api_key_to_state_env",
]

