from PIL import Image
m02 = Image.open("/passport/模板/m02.png")
m03 = Image.open("/data/passport/模板/m03.png")
print(f"m02: {m02.size}")
print(f"m03: {m03.size}")

# Compute key anchor points from m02
import cv2
import numpy as np

m02_arr = np.array(m02.convert('RGB'))
m03_arr = np.array(m03.convert('RGB'))

# PASSPORT in m02: y=1025-1064, x=304-559
pass_m02 = m02_arr[1025:1064, 304:559]
dark = pass_m02 < [100,100,100]
ys, xs = np.where(dark.all(axis=2))
cx_pass_m02 = 304 + xs.min() + (xs.max()-xs.min())//2
cy_pass_m02 = 1025 + ys.min() + (ys.max()-ys.min())//2
print(f"PASSPORT m02: cx={cx_pass_m02}, cy={cy_pass_m02}")

# MOHA in m02: y=1380-1415, x=908-1273
moha_m02 = m02_arr[1380:1415, 908:1273]
dark_m = moha_m02 < [100,100,100]
ys_m, xs_m = np.where(dark_m.all(axis=2))
cx_moha_m02 = 908 + xs_m.min() + (xs_m.max()-xs_m.min())//2
cy_moha_m02 = 1380 + ys_m.min() + (ys_m.max()-ys_m.min())//2
print(f"MOHA m02: cx={cx_moha_m02}, cy={cy_moha_m02}")

# REPUBLIC in m02: y=939-968, x=536-1109
rep_m02 = m02_arr[939:968, 536:1109]
dark_r = rep_m02 < [100,100,100]
ys_r, xs_r = np.where(dark_r.all(axis=2))
cx_rep_m02 = 536 + xs_r.min() + (xs_r.max()-xs_r.min())//2
cy_rep_m02 = 939 + ys_r.min() + (ys_r.max()-ys_r.min())//2
print(f"REPUBLIC m02: cx={cx_rep_m02}, cy={cy_rep_m02}")

# PASSPORT in m03
pass_m03 = m03_arr[1023:1062, 302:557]
dark_p = pass_m03 < [100,100,100]
ys_p, xs_p = np.where(dark_p.all(axis=2))
cx_pass_m03 = 302 + xs_p.min() + (xs_p.max()-xs_p.min())//2
cy_pass_m03 = 1023 + ys_p.min() + (ys_p.max()-ys_p.min())//2
print(f"PASSPORT m03: cx={cx_pass_m03}, cy={cy_pass_m03}")

# MOHA in m03
moha_m03 = m03_arr[1380:1415, 908:1275]
dark_mo = moha_m03 < [100,100,100]
ys_mo, xs_mo = np.where(dark_mo.all(axis=2))
cx_moha_m03 = 908 + xs_mo.min() + (xs_mo.max()-xs_mo.min())//2
cy_moha_m03 = 1380 + ys_mo.min() + (ys_mo.max()-ys_mo.min())//2
print(f"MOHA m03: cx={cx_moha_m03}, cy={cy_moha_m03}")

# REPUBLIC in m03
rep_m03 = m03_arr[939:968, 536:1109]
dark_r3 = rep_m03 < [100,100,100]
ys_r3, xs_r3 = np.where(dark_r3.all(axis=2))
cx_rep_m03 = 536 + xs_r3.min() + (xs_r3.max()-xs_r3.min())//2
cy_rep_m03 = 939 + ys_r3.min() + (ys_r3.max()-ys_r3.min())//2
print(f"REPUBLIC m03: cx={cx_rep_m03}, cy={cy_rep_m03}")

print(f"\n--- Scale calculation ---")
dist_m02 = np.sqrt((cx_moha_m02-cx_pass_m02)**2 + (cy_moha_m02-cy_pass_m02)**2)
dist_m03 = np.sqrt((cx_moha_m03-cx_pass_m03)**2 + (cy_moha_m03-cy_pass_m03)**2)
scale = dist_m03 / dist_m02
print(f"dist_m02: {dist_m02:.2f}, dist_m03: {dist_m03:.2f}, scale: {scale:.4f}")

print(f"\n--- Offset calculation ---")
dx = cx_pass_m03 - cx_pass_m02
dy = cy_pass_m03 - cy_pass_m02
print(f"dx: {dx}, dy: {dy}")

# REPUBLIC check
rep_dx = cx_rep_m03 - cx_rep_m02
rep_dy = cy_rep_m03 - cy_rep_m02
print(f"REPUBLIC dx: {rep_dx}, dy: {rep_dy}")
print(f"m02 REPUBLIC: ({cx_rep_m02}, {cy_rep_m02})")
print(f"m03 REPUBLIC: ({cx_rep_m03}, {cy_rep_m03})")

# Write the lazy script with dual-point affine
