import cv2
import numpy as np
import os
from tkinter import Tk, filedialog

# =========================
# パラメータ（ここだけ調整）
# =========================

# --- クロップ範囲 ---
CROP_TOP = 0.13
CROP_BOTTOM = 0.87
CROP_LEFT = 0.02
CROP_RIGHT = 0.98

# --- プレイヤーネームマスク（左）---
LEFT_MASK_X1 = 0.27
LEFT_MASK_X2 = 0.45

# --- プレイヤーネームマスク（右）---
RIGHT_MASK_X1 = 0.78
RIGHT_MASK_X2 = 0.96

# --- 共通Y範囲 ---
MASK_Y1 = 0.13
MASK_Y2 = 0.20


# =========================
# 日本語パス対応
# =========================
def imread_unicode(path):
    with open(path, "rb") as f:
        data = np.frombuffer(f.read(), np.uint8)
    return cv2.imdecode(data, cv2.IMREAD_COLOR)


def imwrite_unicode(path, img):
    ext = os.path.splitext(path)[1]
    _, buf = cv2.imencode(ext, img)
    with open(path, "wb") as f:
        f.write(buf)


# =========================
# メイン処理
# =========================
def process_bluearchive_result(input_path, output_path):
    img = imread_unicode(input_path)

    if img is None:
        print("画像読み込み失敗:", input_path)
        return

    h, w = img.shape[:2]

    # ===== クロップ =====
    cropped = img[
        int(h * CROP_TOP):int(h * CROP_BOTTOM),
        int(w * CROP_LEFT):int(w * CROP_RIGHT)
    ]

    ch, cw = cropped.shape[:2]

    # ===== マスク（左）=====
    cv2.rectangle(
        cropped,
        (int(cw * LEFT_MASK_X1), int(ch * MASK_Y1)),
        (int(cw * LEFT_MASK_X2), int(ch * MASK_Y2)),
        (246, 247, 247),
        -1
    )

    # ===== マスク（右）=====
    cv2.rectangle(
        cropped,
        (int(cw * RIGHT_MASK_X1), int(ch * MASK_Y1)),
        (int(cw * RIGHT_MASK_X2), int(ch * MASK_Y2)),
        (216, 225, 255),
        -1
    )

    imwrite_unicode(output_path, cropped)
    print("保存:", output_path)


# =========================
# ファイル選択
# =========================
Tk().withdraw()

file_path = filedialog.askopenfilename(
    title="スクショを選択",
    filetypes=[("Image files", "*.png;*.jpg;*.jpeg")]
)

if file_path:
    base, ext = os.path.splitext(file_path)
    output_path = base + "_processed" + ext

    process_bluearchive_result(file_path, output_path)