#!/usr/bin/env python3
"""Fix pass 3: precise positioning for operators and The Ask"""

import json, requests

with open('/root/.config/gws/credentials.json') as f:
    creds = json.load(f)
with open('/root/.config/gws/client_secret.json') as f:
    client = json.load(f)
ci = client.get('installed', client.get('web', {}))

resp = requests.post('https://oauth2.googleapis.com/token', data={
    'client_id': ci['client_id'],
    'client_secret': ci['client_secret'],
    'refresh_token': creds['refresh_token'],
    'grant_type': 'refresh_token'
})
access_token = resp.json()['access_token']
headers = {'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json'}

PRES_ID = '1IvDHJ53PEYvge41LdLc7Tyb5U4xOmID7GjHlIYHarJY'
SLIDES_API = 'https://slides.googleapis.com/v1/presentations'
PT = 12700
INCH = 914400
PAGE_W = 9144000
PAGE_H = 5143500
MARGIN_LEFT = int(INCH * 0.8)

resp = requests.get(f'{SLIDES_API}/{PRES_ID}', headers=headers)
pres = resp.json()

reqs = []

# ─── Debug: inspect actual elements on slide 4 and 9 ───────────────────
for slide_idx in [4, 9]:
    print(f"\n=== Slide {slide_idx} elements ===")
    for el in pres['slides'][slide_idx]['pageElements']:
        eid = el['objectId']
        t = el.get('transform', {})
        s = el.get('size', {})
        
        # Actual rendered position
        sx = t.get('scaleX', 1)
        sy = t.get('scaleY', 1)
        tx = t.get('translateX', 0)
        ty = t.get('translateY', 0)
        w = s.get('width', {}).get('magnitude', 0) * sx
        h = s.get('height', {}).get('magnitude', 0) * sy
        
        text = ""
        if 'shape' in el and 'text' in el.get('shape', {}):
            for te in el['shape']['text'].get('textElements', []):
                if 'textRun' in te:
                    text += te['textRun']['content']
            text = text.strip()[:50]
        elif 'image' in el:
            text = "[IMAGE]"
        elif 'line' in el:
            text = "[LINE]"
        
        print(f"  {eid}: pos=({tx/INCH:.2f}\",{ty/INCH:.2f}\") size=({w/INCH:.2f}\"x{h/INCH:.2f}\") | {text}")

# ─── Fix operator photos: set absolute reasonable size ──────────────────
print("\n--- Fixing operator photos ---")
photo_targets = {
    # First photo (Assaf) → position at left column
    0: {"x": MARGIN_LEFT, "y": int(PAGE_H * 0.37)},
    # Second photo (Lukas) → position at right column
    1: {"x": MARGIN_LEFT + int((PAGE_W - MARGIN_LEFT * 2 - INCH * 0.5) / 2) + int(INCH * 0.5), "y": int(PAGE_H * 0.37)},
}

photo_idx = 0
for el in pres['slides'][4]['pageElements']:
    if 'image' in el:
        eid = el['objectId']
        target = photo_targets[photo_idx]
        orig_w = el['size']['width']['magnitude']
        orig_h = el['size']['height']['magnitude']
        
        # Target: 1.1" x 1.1" 
        target_w = int(INCH * 1.1)
        target_h = int(INCH * 1.1)
        
        reqs.append({
            "updatePageElementTransform": {
                "objectId": eid,
                "applyMode": "ABSOLUTE",
                "transform": {
                    "scaleX": target_w / orig_w,
                    "scaleY": target_h / orig_h,
                    "translateX": target["x"],
                    "translateY": target["y"],
                    "unit": "EMU"
                }
            }
        })
        print(f"  Photo {photo_idx} ({eid}): scale {target_w/orig_w:.4f} x {target_h/orig_h:.4f}, pos ({target['x']/INCH:.2f}\", {target['y']/INCH:.2f}\")")
        photo_idx += 1

# ─── Fix The Ask heading/body positions ─────────────────────────────────
print("\n--- Fixing The Ask slide ---")
for el in pres['slides'][9]['pageElements']:
    if 'shape' not in el or 'text' not in el.get('shape', {}):
        continue
    text = ""
    for te in el['shape']['text'].get('textElements', []):
        if 'textRun' in te:
            text += te['textRun']['content']
    
    eid = el['objectId']
    orig_w = el['size']['width']['magnitude']
    orig_h = el['size']['height']['magnitude']
    
    if "What would Brandwatch" in text:
        # Heading: top portion, 28pt, width ~7.5", height ~2"
        target_y = int(PAGE_H * 0.15)
        target_h = int(INCH * 2.2)
        target_w = int(INCH * 7.5)
        reqs.append({
            "updatePageElementTransform": {
                "objectId": eid,
                "applyMode": "ABSOLUTE",
                "transform": {
                    "scaleX": target_w / orig_w,
                    "scaleY": target_h / orig_h,
                    "translateX": MARGIN_LEFT,
                    "translateY": target_y,
                    "unit": "EMU"
                }
            }
        })
        print(f"  Heading ({eid}): y={target_y/INCH:.2f}\", h={target_h/INCH:.2f}\"")
    
    elif "60-minute" in text:
        # Body: below the heading, at ~62% of page height
        target_y = int(PAGE_H * 0.62)
        target_h = int(INCH * 1.8)
        target_w = int(INCH * 5.5)
        reqs.append({
            "updatePageElementTransform": {
                "objectId": eid,
                "applyMode": "ABSOLUTE",
                "transform": {
                    "scaleX": target_w / orig_w,
                    "scaleY": target_h / orig_h,
                    "translateX": MARGIN_LEFT,
                    "translateY": target_y,
                    "unit": "EMU"
                }
            }
        })
        print(f"  Body ({eid}): y={target_y/INCH:.2f}\", h={target_h/INCH:.2f}\"")

# ─── Execute ────────────────────────────────────────────────────────────────
print(f"\nSending {len(reqs)} requests...")
for i, req in enumerate(reqs):
    r = requests.post(f"{SLIDES_API}/{PRES_ID}:batchUpdate", headers=headers, json={"requests": [req]})
    key = list(req.keys())[0]
    if r.status_code != 200:
        print(f"  FAILED {i} ({key}): {r.text[:200]}")
    else:
        print(f"  OK {i} ({key})")

print("\nDone!")
