"""Supporting helpers for the article's two equivalent provisioning examples."""

import os
import re
from pathlib import Path

import chalkcompute as cc

HOST_POOL_ID = os.environ["CHALK_WORKSPACE_HOST_POOL_ID"]


def provisioner_image():
    return (
        cc.Image.debian_slim("3.12")
        .pip_install(["chalkcompute==2.13.8", "connectrpc==0.12.1"])
        .env({"CHALK_WORKSPACE_HOST_POOL_ID": HOST_POOL_ID})
        .add_local_file(str(Path(__file__).resolve()), "/app/workspace_helpers.py")
    )


def developer_image():
    return cc.Image.base("node:26.13.1-bookworm")


def install_dev_tools(image):
    return (
        image.apt_install(["ca-certificates", "curl", "git", "neovim", "zsh"])
        .with_tmux()
        .with_gh()
        .run_commands(
            "npm install -g @openai/codex@0.163.0",
            "curl -fsSL https://api.chalk.ai/install.sh -o /tmp/install-chalk.sh && sh /tmp/install-chalk.sh v1.54.15",
            "curl -fsSL https://github.com/herdrdev/herdr/releases/download/v0.9.5/herdr-linux-x86_64 "
            "-o /usr/local/bin/herdr && chmod 755 /usr/local/bin/herdr",
            "printf '%s\\n' 'export EDITOR=nvim' 'alias ll=\"ls -lah\"' "
            "'HISTFILE=~/.zsh_history' 'HISTSIZE=10000' 'SAVEHIST=10000' "
            "'autoload -Uz compinit && compinit' > /root/.zshrc",
            "printf '%s\\n' 'export PATH=\"$HOME/.chalk/bin:$PATH\"' > /root/.zprofile",
            "mkdir -p /workspace",
        )
        .env(
            {
                "EDITOR": "nvim",
                "SHELL": "/bin/zsh",
                "PATH": "/root/.chalk/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
            }
        )
        .workdir("/workspace")
    )


def create_network_policy():
    return cc.NetworkPolicy(allowed_hosts=["api.github.com", "github.com", "*.chalk.ai"])


def validate_workspace(name_suffix, lifetime_minutes, shared_volume_name):
    for label in (name_suffix, shared_volume_name):
        if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,39}", label):
            raise ValueError("Use lowercase labels with digits/hyphens, max 40 characters")
    if not 15 <= lifetime_minutes <= 10080:
        raise ValueError("Choose a lifetime between 15 minutes and seven days")


def make_sandbox_workspace(*, name_suffix, image, lifetime_minutes, shared_volume_name, github_secret_name):
    validate_workspace(name_suffix, lifetime_minutes, shared_volume_name)
    cc.Volume(shared_volume_name).reload()
    sandbox = cc.Sandbox(
        name=f"dev-{name_suffix}",
        image=image,
        cpu="8",
        memory="16Gi",
        lifetime=f"{lifetime_minutes * 60}s",
        compute_class=cc.ComputeClass.HOST,
        host_pool_id=HOST_POOL_ID,
        chalk_identity=True,
        network_policy=create_network_policy(),
        resource_detectors=[cc.ResourceDetector.GITHUB_PULL_REQUESTS],
        entrypoint=["sleep", "infinity"],
    ).mount_volume(shared_volume_name, "/workspace/shared")
    if github_secret_name:
        sandbox.add_credentials(
            "api.github.com",
            cc.Secret.from_chalk_env(github_secret_name, alias="GH_TOKEN"),
        )
    return sandbox.run()
