# tools/cli/brew.py - Isolated Homebrew for Mugi (~/.mugi/homebrew).
# Moved from tools/mugi_brew.py. Allows the agent to install software (e.g. ffmpeg)
# via brew without affecting the user's system.
from __future__ import annotations

import json
import os
import sys
import time

from langchain_core.tools import tool

from tools._logging import _debug_log, _emit_input_status
from tools.mugi_brew_bootstrap import get_mugi_brew_bin, get_mugi_homebrew_bin_dir, _run_brew, ensure_mugi_homebrew_core
from tools.system import _load_app_prefs_tools, wait_for_shell_confirm
from persistence import MUGI_DIR, MUGI_LOGS_DIR

_DEBUG_LOG_PATH = os.path.join(MUGI_LOGS_DIR, "mugi_brew_debug.log")


def _run_brew_log(cmd: list[str], timeout: int = 300) -> tuple[bool, str]:
    """_run_brew with debug logging."""
    _debug_log(f"[mugi_brew] Running: {' '.join(cmd)}")
    return _run_brew(cmd, timeout=timeout)


@tool
def ensure_mugi_homebrew() -> str:
    """Install or update Mugi's isolated Homebrew at ~/.mugi/homebrew. Use this first so the agent can then install software (e.g. ffmpeg) without affecting the rest of your system. Clones via dulwich (no system git); requires network. No sudo."""
    _debug_log("ensure_mugi_homebrew: checking / updating Mugi Homebrew at ~/.mugi/homebrew", "INFO")
    _emit_input_status("Setting up Homebrew…")
    ok, msg = ensure_mugi_homebrew_core(python_for_dulwich=sys.executable)
    if not ok:
        return msg
    return msg or "Homebrew is ready."


@tool
def mugi_brew_install(formula: str) -> str:
    """Install a Homebrew formula using Mugi's isolated Homebrew (~/.mugi/homebrew). Does not affect your system Homebrew or system PATH. Requires user confirmation. Use ensure_mugi_homebrew first if you have not already. Input: the formula name (e.g. ffmpeg, yt-dlp, imagemagick). If installation fails, report the error to the user; do not try alternative methods like cloning the project repository or building from source."""
    formula = (formula or "").strip()
    _emit_input_status(f"Installing {formula}…")
    _debug_log(f"brew install {formula}: starting (user confirmation may be required)", "INFO")
    if not formula:
        return "No formula name provided."
    prefs = _load_app_prefs_tools()
    if not prefs.get("allow_shell_execute", False):
        return "Shell/brew install is disabled in app preferences. Enable 'Allow shell execution' in Preferences first."
    brew_bin = get_mugi_brew_bin()
    if not brew_bin:
        return "Mugi's Homebrew is not installed. Use ensure_mugi_homebrew first, then try again."
    # Show user the exact command we will run
    display_cmd = f"{brew_bin} install {formula}"
    choice = wait_for_shell_confirm(display_cmd, use_allow_cache=True)
    if choice is None:
        return "Install confirmation timed out (no response from user)."
    if choice == "deny":
        return "Install denied by user."
    ok, msg = _run_brew_log(["install", formula], timeout=600)
    _debug_log(f"brew install {formula}: {'OK' if ok else 'failed'} — {(msg[:120] + '...') if msg and len(msg) > 120 else (msg or 'no message')}", "INFO")
    try:
        os.makedirs(MUGI_LOGS_DIR, exist_ok=True)
        log_path = os.path.join(MUGI_LOGS_DIR, "mugi_brew_debug.log")
        with open(log_path, "a") as f:
            f.write(
                json.dumps(
                    {
                        "id": "mugi_brew_install_result",
                        "timestamp": int(time.time() * 1000),
                        "formula": formula,
                        "ok": ok,
                        "msg_preview": (msg or "")[:500],
                    }
                )
                + "\n"
            )
    except Exception:
        pass
    if ok:
        return f"Success: {formula} is installed and ready to use.\n{msg or ''}"
    return (
        f"Installation failed: {formula} is NOT installed. The download/install did not complete.\n"
        f"Error: {msg}\n\n"
        "Do not try alternative methods (e.g. cloning the repo). Tell the user the install failed. "
        "For yt-dlp, suggest: use install_cli_package('yt-dlp') to install it in an isolated venv, "
        "then run the bundled yt-dlp plugin tool (download_video_yt_dlp) again."
    )
