"""Experimental `dialoghelper` capabilities."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_experimental.ipynb.

# %% auto 0
__all__ = ['create_iife', 'capture_screen']

# %% ../nbs/01_experimental.ipynb
from importlib import resources
import uuid
from fasthtml.common import Div, Script
from time import sleep
import base64
import json
import time
from claudette import ToolResult
from .core import *
from dataclasses import dataclass
from httpx import get as xget, post as xpost

# %% ../nbs/01_experimental.ipynb
_js_loaded = False

def _load_screenshot_js():
    "Load screenshot capability if not already present."
    global _js_loaded
    if _js_loaded:
        print("screenshot.js already loaded")
        return
    js_content = (resources.files('dialoghelper') / 'screenshot.js').read_text()
    add_html(Div(Script(js_content), hx_swap_oob='beforeend:#js-script'))
    print("Added screenshot.js")
    _js_loaded = True

# %% ../nbs/01_experimental.ipynb
def create_iife(code: str) -> str:
    "Wrap javascript code string in an IIFE"
    return f'''
(async () => {{
{code}
}})();
'''

# %% ../nbs/01_experimental.ipynb
def capture_screen():
    "Capture current desktop returning the screenshot as a ToolImageResult."
    _load_screenshot_js()        
    data_id = str(uuid.uuid4())  # Generate random ID for data communication
    screenshot_code = f'captureScreenAndUpload("{data_id}");'
    trigger_script = create_iife(screenshot_code)
    add_html(Div(Script(trigger_script), hx_swap_oob=f'beforeend:#js-script'))
    max_attempts = 50
    for attempt in range(max_attempts):
        result = xpost('http://localhost:5001/pop_data_', data={'data_id': data_id})
        if result.status_code == 200:
            try:
                if not result.text.strip():
                    time.sleep(0.5)
                    continue
                data = result.json() # data is a dict
                if 'error' in data: return f"Screenshot failed: {data['error']}"
                if 'img_data' in data and 'img_type' in data:
                    return ToolResult(data=data['img_data'], result_type=data['img_type'])
                return f"Screenshot data incomplete: {data}"
            except json.JSONDecodeError as e: print(f"JSON decode error: {e}, Raw text: '{result.text}'")
            except Exception as e: print(f"Error processing screenshot data: {e}")
        time.sleep(0.5)
    return "Screenshot capture timed out"
