"""Docker deployment helpers for ogmem onboard."""

from __future__ import annotations

import logging
import os
import subprocess
from pathlib import Path

from cli.lib.config_loader import get_project_root

logger = logging.getLogger(__name__)


def generate_deploy_env(
    llm_config: dict,
    db_config: dict | None = None,
    container_config: dict | None = None,
    output_path: Path | None = None,
) -> Path:
    """Generate a deploy.env file from onboarding parameters."""
    root = get_project_root()
    output_path = output_path or root / "deploy" / "deploy.env"

    lines = [
        "# Generated by ogmem onboard",
        "",
        "LLM_PROVIDER=\"{}\"".format(llm_config["provider"]),
        "LLM_API_KEY=\"{}\"".format(llm_config.get("api_key", "")),
        "LLM_BASE_URL=\"{}\"".format(llm_config.get("base_url", "")),
        "LLM_MODEL=\"{}\"".format(llm_config.get("model", "")),
    ]

    if db_config:
        og_enabled = db_config.get("enable_opengauss", True)
        lines.append("")
        lines.append("ENABLE_OPENGAUSS=\"{}\"".format("true" if og_enabled else "false"))
        if og_enabled:
            lines.append("OG_HOST_PORT=\"{}\"".format(db_config.get("port", "15432")))
        lines.append("OPENGAUSS_HOST_IP=\"{}\"".format(db_config.get("host_ip", "127.0.0.1")))

    if container_config:
        lines.append("")
        lines.append("OPENCLAW_HOST_IP=\"{}\"".format(container_config.get("host_ip", "127.0.0.1")))
        if container_config.get("container_name"):
            lines.append("OGMEM_CONTAINER_NAME=\"{}\"".format(container_config["container_name"]))
        if container_config.get("openclaw_container_name"):
            lines.append("OPENCLAW_CONTAINER_NAME=\"{}\"".format(container_config["openclaw_container_name"]))

    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
    return output_path


def generate_docker_config(
    llm_config: dict,
    embedding_config: dict,
    vdb_config: dict,
    output_path: Path | None = None,
) -> Path:
    """Generate an ogmemory.yaml for Docker deployment with ${ENV_VAR} references."""
    root = get_project_root()
    output_path = output_path or root / "deploy" / "ogmemory.yaml"

    vdb_type = vdb_config.get("type", "opengauss")
    vdb_conn = vdb_config.get("connection_string", "host=127.0.0.1 port=8799 dbname=postgres user=gaussdb password=CHANGE_ME")

    content = f"""# Generated by ogmem onboard (Docker mode)
# Supports ${{ENV_VAR}} references from deploy.env

llm:
  provider: "${{LLM_PROVIDER}}"
  api_key: "${{LLM_API_KEY}}"
  base_url: "${{LLM_BASE_URL}}"
  model: "${{LLM_MODEL}}"
  temperature: 0.1

embedding:
  provider: {embedding_config.get('provider', 'openai')}
  model: "{embedding_config.get('model', 'text-embedding-v4')}"
  base_url: "${{LLM_BASE_URL}}"
  api_key: "${{LLM_API_KEY}}"

vector_db:
  type: {vdb_type}
  connection_string: "{vdb_conn}"
  dimension: {embedding_config.get('dimension', 1024)}
  table_name: vector_index
  pool_size: 5

service:
  http_port: 8090
  workers: 2

storage:
  backend: sql

agfs:
  base_url: "http://127.0.0.1:1833"
  mount_prefix: /local/plugin

index:
  interval: 15
  workers: 1

identity:
  account_id: "acct-demo"
  user_id: "u-alice"
  agent_id: "main"
"""
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(content, encoding="utf-8")
    return output_path


def deploy_docker(
    env_file: Path | None = None,
    password: str | None = None,
) -> int:
    """Run deploy.sh to start Docker containers.

    Returns the exit code from deploy.sh.
    """
    root = get_project_root()
    deploy_sh = root / "deploy" / "deploy.sh"
    if not deploy_sh.exists():
        logger.error("deploy.sh not found at %s", deploy_sh)
        return 1

    env_file = env_file or root / "deploy" / "deploy.env"
    cmd = ["bash", str(deploy_sh)]
    if password:
        cmd.extend(["-password", password])

    env = os.environ.copy()
    env["DEPLOY_ENV_FILE"] = str(env_file)

    logger.info("Running: %s", " ".join(cmd))
    result = subprocess.run(cmd, cwd=str(root), env=env)
    return result.returncode