"""Generate continuous-ops worker artifacts (Python loop + JSON config)."""

from __future__ import annotations

import json
import os
import shlex
import shutil
import sys
from pathlib import Path


CONFIG_NAME = "run_loop_config.json"


def copy_template_snapshot(run_dir: Path) -> Path | None:
    """Deprecated: bash template removed; keep hook for callers expecting a Path."""
    return None


def _heredoc_payload(tick_prompt: str) -> str:
    """Unused — kept for backwards compatibility with external importers."""
    return tick_prompt


def build_runtime_preamble_bash() -> str:
    """Deprecated: loop is Python; tmux may still ``source`` venv in the wizard command."""
    ve = (os.environ.get("VIRTUAL_ENV") or "").strip()
    if not ve:
        return ""
    act = shlex.quote(f"{ve.rstrip('/')}/bin/activate")
    return f"source {act}\n"


def render_loop_script(
    *,
    run_dir: Path,
    tick_seconds: int,
    tick_prompt: str,
    privileged: bool,
    cai_argv: list[str],
    python_bin: str | None = None,
    log_full_days: int = 7,
    log_delete_after_days: int = 15,
) -> Path:
    """Write ``run_loop_config.json`` + ``run_loop.py`` under *run_dir*; return path to ``run_loop.py``."""
    run_dir.mkdir(parents=True, exist_ok=True)
    py = python_bin or sys.executable
    cfg = {
        "tick_seconds": int(tick_seconds),
        "tick_prompt": tick_prompt,
        "privileged": bool(privileged),
        "cai_argv": [str(x) for x in cai_argv],
        "python_interpreter": str(py),
        "log_full_days": max(1, int(log_full_days)),
        "log_delete_after_days": max(int(log_full_days) + 1, int(log_delete_after_days)),
        "entry_script": "run_loop.py",
        "worker_agent_type": "blueteam_agent",
    }
    (run_dir / CONFIG_NAME).write_text(json.dumps(cfg, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

    runner_body = (
        f"#!{py}\n"
        "# Generated by CAI continuous_ops — do not edit by hand (regenerate from the wizard).\n"
        "from __future__ import annotations\n"
        "import sys\n"
        "from pathlib import Path\n"
        "if __name__ == '__main__':\n"
        "    _here = Path(__file__).resolve()\n"
        "    from cai.continuous_ops.loop_runner import main\n"
        "    raise SystemExit(main(_here.parent, entry_path=_here))\n"
    )
    out_path = run_dir / "run_loop.py"
    out_path.write_text(runner_body, encoding="utf-8")
    try:
        out_path.chmod(out_path.stat().st_mode | 0o111)
    except (OSError, NotImplementedError):
        pass
    return out_path


def default_cai_argv() -> list[str]:
    """Argv prefix for ``cai`` in the worker (respects yolo / unrestricted flags)."""
    wh = shutil.which("cai")
    if wh:
        argv = [str(Path(wh).resolve())]
    else:
        argv = [sys.executable, "-m", "cai"]
    if os.getenv("CAI_YOLO", "").lower() in ("1", "true", "yes"):
        argv.append("--yolo")
    elif os.getenv("CAI_UNRESTRICTED", "").lower() in ("1", "true", "yes"):
        argv.append("--unrestricted")
    return argv
