#!/usr/bin/env python3
"""Ensure optional cairosvg dependencies are ready for visual-builder on macOS."""

import argparse
import os
import platform
import shutil
import subprocess
import sys


def _darwin_env():
    env = os.environ.copy()
    homebrew_lib = "/opt/homebrew/lib"
    if os.path.isdir(homebrew_lib):
        env.setdefault("DYLD_FALLBACK_LIBRARY_PATH", homebrew_lib)
    return env


def _manual_instructions():
    print("Automatic cairosvg setup is only supported on macOS.", file=sys.stderr)
    print("Manual setup:", file=sys.stderr)
    print("  1. Install the cairo system library for your platform.", file=sys.stderr)
    print("  2. pip install -r scripts/requirements-optional.txt", file=sys.stderr)
    return 1


def _brew_formula_installed(formula):
    result = subprocess.run(
        ["brew", "list", "--versions", formula],
        capture_output=True,
        text=True,
        check=False,
    )
    if result.returncode == 0:
        return True
    if result.returncode == 1:
        return False
    raise RuntimeError(
        f"Unable to determine whether Homebrew formula '{formula}' is installed.\n"
        f"stdout: {result.stdout}\nstderr: {result.stderr}"
    )


def _run(cmd, env=None):
    print(f"+ {' '.join(cmd)}")
    result = subprocess.run(cmd, env=env, check=False)
    if result.returncode != 0:
        raise RuntimeError(f"Command failed with exit code {result.returncode}: {' '.join(cmd)}")


def _verify_import():
    env = _darwin_env()
    result = subprocess.run(
        [sys.executable, "-c", "import cairosvg"],
        env=env,
        capture_output=True,
        text=True,
        check=False,
    )
    if result.returncode == 0:
        print("Verified: cairosvg imports successfully.")
        return True

    print("cairosvg import verification failed.", file=sys.stderr)
    if result.stdout.strip():
        print(result.stdout.strip(), file=sys.stderr)
    if result.stderr.strip():
        print(result.stderr.strip(), file=sys.stderr)
    return False


def _check_ready():
    if platform.system() != "Darwin":
        return _manual_instructions()

    brew_path = shutil.which("brew")
    if not brew_path:
        print("Homebrew is required for automatic macOS setup but was not found.", file=sys.stderr)
        print("Install Homebrew, then run: python3 scripts/ensure_cairosvg.py", file=sys.stderr)
        return 1

    print(f"Homebrew found: {brew_path}")
    missing = [formula for formula in ("cairo", "pkg-config") if not _brew_formula_installed(formula)]
    if missing:
        print(
            "Missing Homebrew formula(s): " + ", ".join(missing) + ".",
            file=sys.stderr,
        )
        print("Run: python3 scripts/ensure_cairosvg.py", file=sys.stderr)
        return 1

    if not _verify_import():
        print("Run: python3 scripts/ensure_cairosvg.py", file=sys.stderr)
        return 1

    print("cairosvg is ready for visual-builder.")
    return 0


def _install():
    if platform.system() != "Darwin":
        return _manual_instructions()

    brew_path = shutil.which("brew")
    if not brew_path:
        print("Homebrew is required for automatic macOS setup but was not found.", file=sys.stderr)
        print("Install Homebrew first: https://brew.sh", file=sys.stderr)
        return 1

    print(f"Homebrew found: {brew_path}")
    missing = [formula for formula in ("cairo", "pkg-config") if not _brew_formula_installed(formula)]
    if missing:
        _run(["brew", "install", *missing], env=_darwin_env())
    else:
        print("Homebrew formulae already installed: cairo, pkg-config")

    _run([sys.executable, "-m", "pip", "install", "cairosvg"], env=_darwin_env())

    if not _verify_import():
        print("Unexpected state: installation completed but cairosvg still does not import.", file=sys.stderr)
        return 1

    print("cairosvg setup completed successfully.")
    return 0


def main():
    parser = argparse.ArgumentParser(
        description="Check or install optional cairosvg dependencies for visual-builder."
    )
    parser.add_argument(
        "--check",
        action="store_true",
        help="Check whether cairosvg is ready without installing anything.",
    )
    args = parser.parse_args()

    if args.check:
        sys.exit(_check_ready())
    sys.exit(_install())


if __name__ == "__main__":
    main()
