import base64, sys, time
from pathlib import Path
sys.path.insert(0, '/home/ubuntu/.hermes/hermes-agent')
from agent.auxiliary_client import _read_codex_access_token, _codex_cloudflare_headers
import openai

OUTDIR = Path('/home/ubuntu/.hermes/artifacts/panel-install-site/assets')
OUTDIR.mkdir(parents=True, exist_ok=True)

def make_client():
    token = _read_codex_access_token()
    if not token:
        raise SystemExit('No Codex token')
    return openai.OpenAI(
        api_key=token,
        base_url='https://chatgpt.com/backend-api/codex',
        default_headers=_codex_cloudflare_headers(token),
    )

client = make_client()

base_style = """
Create a clean IKEA-style assembly manual illustration: black and dark gray vector line art on an off-white paper background, minimal, precise, friendly, no photorealism, no color except very subtle warm yellow glow for LED where requested. Use numbered circles only; avoid written words and avoid fake labels. Use simple pictograms: wall, wood frame, drill, screws, LED strip, adhesive, vertical slat panels, hands. Keep empty margins. The image must be usable as an instruction drawing inside a Spanish DIY website.
""".strip()

prompts = [
    (
        'ikea-01-measure-frame.png',
        base_style + """
Sheet 1: measured planning for a wall-mounted wood slat panel. Show four numbered mini-panels:
1) A rectangular wall being measured with tape measure; a narrow tall panel area is positioned closer to the right side of the wall, not centered.
2) The visible panel is almost floor-to-ceiling, leaving tiny top and bottom margins.
3) Behind it, a smaller hidden wooden frame sits inset from all four edges, with a clear lip/overhang hiding the frame.
4) A cut list visual: two long vertical wooden pieces and five shorter horizontal cross pieces laid on the floor.
No text except numbers 1,2,3,4. Include clear dimension arrows but without readable text.
""".strip()
    ),
    (
        'ikea-02-fix-led.png',
        base_style + """
Sheet 2: building and mounting the wooden frame plus LED. Show four numbered mini-panels:
1) Assemble a rectangular wooden frame on the floor: two vertical sides and five horizontal crossbars; screws at corners and crossbars.
2) Lift/present the frame onto a wall, use a level, mark drill holes.
3) Drill into masonry wall, insert wall plugs/tarugos, screw the frame firmly to the wall.
4) Apply warm LED strip around the OUTER EDGE/SIDE of the frame, not the front face; show a soft warm halo glowing behind the future panel and a small accessible power supply box off to one side.
No text except numbers 1,2,3,4.
""".strip()
    ),
    (
        'ikea-03-glue-panels.png',
        base_style + """
Sheet 3: attaching the vertical EPS wood slat panels. Show four numbered mini-panels:
1) Apply construction adhesive dots/short beads on the five horizontal frame crossbars, not everywhere.
2) Place the first vertical slat panel straight using a level; press at the five crossbar contact points.
3) Repeat with eleven vertical slat panels side-by-side, tight seams, aligning top and bottom.
4) Use painter's tape to hold panels while curing; final view shows a clean tall wood slat panel with hidden warm LED halo around edges.
No text except numbers 1,2,3,4.
""".strip()
    ),
]

def generate(prompt, out):
    image_b64 = None
    with client.responses.stream(
        model='gpt-5.4',
        store=False,
        instructions='You are an assistant that must fulfill image generation requests by using the image_generation tool when provided.',
        input=[{
            'type': 'message',
            'role': 'user',
            'content': [{'type': 'input_text', 'text': prompt}],
        }],
        tools=[{
            'type': 'image_generation',
            'model': 'gpt-image-2',
            'size': '1024x1536',
            'quality': 'medium',
            'output_format': 'png',
            'background': 'opaque',
            'partial_images': 1,
        }],
        tool_choice={
            'type': 'allowed_tools',
            'mode': 'required',
            'tools': [{'type': 'image_generation'}],
        },
    ) as stream:
        for event in stream:
            t = getattr(event, 'type', '')
            if t == 'response.image_generation_call.partial_image':
                partial = getattr(event, 'partial_image_b64', None)
                if partial:
                    image_b64 = partial
            elif t == 'response.output_item.done':
                item = getattr(event, 'item', None)
                if getattr(item, 'type', None) == 'image_generation_call':
                    result = getattr(item, 'result', None)
                    if result:
                        image_b64 = result
        final = stream.get_final_response()
    for item in getattr(final, 'output', None) or []:
        if getattr(item, 'type', None) == 'image_generation_call':
            result = getattr(item, 'result', None)
            if result:
                image_b64 = result
    if not image_b64:
        raise RuntimeError(f'No image result for {out}')
    out.write_bytes(base64.b64decode(image_b64))
    print(out)

for filename, prompt in prompts:
    out = OUTDIR / filename
    if out.exists() and out.stat().st_size > 10000:
        print(f'skip existing {out}')
        continue
    generate(prompt, out)
    time.sleep(1)
