#!/usr/bin/env python3
"""Optional real-browser web-act smoke (not run by default pytest).

Exits 0 when Playwright can run a minimal harness script; 1 otherwise.
"""
from __future__ import annotations

import json
import os
import sys
import tempfile


def main() -> int:
    repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    if repo_root not in sys.path:
        sys.path.insert(0, repo_root)

    try:
        from utils.playwright_runner import playwright_available, playwright_browsers_ready
        from tools.web_act import web_act_enabled
        from utils.app_prefs_store import load_app_prefs_cached
    except Exception as exc:
        print(f"import failed: {exc}", file=sys.stderr)
        return 1

    prefs = load_app_prefs_cached() or {}
    if not prefs.get("allow_web_act_scripts"):
        print("allow_web_act_scripts pref is off", file=sys.stderr)
        return 1
    if not web_act_enabled():
        print("[web_act].enabled is false", file=sys.stderr)
        return 1
    if not playwright_available():
        print("Playwright package not available", file=sys.stderr)
        return 1
    ready, detail = playwright_browsers_ready(use_cache=False)
    if not ready:
        print(detail or "Playwright browsers not ready", file=sys.stderr)
        return 1

    ws = tempfile.mkdtemp(prefix="mugi_web_act_smoke_")
    os.environ["MUGI_WORKSPACE"] = ws
    try:
        from tools.web_act import run_web_script, write_web_act_file
        from utils.web_act_templates import EXPLORE_PY_TEMPLATE

        try:
            import persistence

            persistence.set_current_agent_thread_id("web_act_smoke")
        except Exception:
            pass
        write_web_act_file.invoke({"relative_path": "smoke.py", "content": EXPLORE_PY_TEMPLATE})
        out = run_web_script.invoke({"script_path": "smoke.py", "fresh_run": True})
        if "exit_code: 0" not in out or "result_ok: True" not in out:
            print(out, file=sys.stderr)
            return 1
        print("web_act smoke ok")
        return 0
    except Exception as exc:
        print(f"smoke run failed: {exc}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
