import base64, os, sys
from pathlib import Path

# Use Hermes' existing Codex OAuth helper.
sys.path.insert(0, '/home/ubuntu/.hermes/hermes-agent')
from agent.auxiliary_client import _read_codex_access_token, _codex_cloudflare_headers
import openai

SRC = Path('/home/ubuntu/.hermes/image_cache/img_22336c28cebc.jpeg')
OUT = Path('/home/ubuntu/.hermes/cache/images/openai_codex_gpt-image-2_living_panel_right_edit.png')

prompt = """
Edit the attached living room photo, preserving the actual room, camera angle, furniture, window, sofa, plants, ceiling, and lighting. Do NOT invent a different room.

Add a realistic vertical warm-oak wood slat / acoustic wall panel installation onto the MAIN WHITE WALL, using these exact real-world proportions:
- wall is 310 cm wide x 255 cm high
- panel visible face is 125.4 cm wide x 250 cm high (11 vertical slats, each about 11.4 cm wide)
- because the panel is 250 cm tall on a 255 cm wall, it should nearly span floor-to-ceiling, with only a tiny margin at top and bottom
- position it closer to the RIGHT side of the main wall, not centered: leave about 35-45 cm real-world margin to the right wall/corner, and the rest of the empty wall to the left
- keep the panel on the wall plane behind the sofa and objects; foreground sofa/plants/clutter must stay in front naturally
- include a subtle warm indirect LED halo around the panel edges, produced by a hidden wooden frame behind it; no visible LED dots
- make the scale believable and match the perspective of the original photo
- remove/cover any small wall shelf only if it is where the new panel would be installed

The result should look like an interior design mockup of the SAME photograph after installation, realistic, not a poster or collage, no labels, no diagrams.
""".strip()

with open(SRC, 'rb') as f:
    b64 = base64.b64encode(f.read()).decode('ascii')

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

image_b64 = None
with client.responses.stream(
    model='gpt-5.4',
    store=False,
    instructions='You are an image editing assistant. You must use the image_generation tool to create the edited output image from the provided input photo.',
    input=[{
        'type': 'message',
        'role': 'user',
        'content': [
            {'type': 'input_text', 'text': prompt},
            {'type': 'input_image', 'image_url': f'data:image/jpeg;base64,{b64}'},
        ],
    }],
    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 SystemExit('No image result')
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_bytes(base64.b64decode(image_b64))
print(OUT)
