from selenium import webdriver
import json
import time

def fix_cookie(cookie):
    # Normalisasi sameSite
    if "sameSite" in cookie:
        value = str(cookie["sameSite"]).strip().lower()
        if value == "strict":
            cookie["sameSite"] = "Strict"
        elif value == "lax":
            cookie["sameSite"] = "Lax"
        elif value in ["none", "no_restriction"]:
            cookie["sameSite"] = "None"
        else:
            cookie.pop("sameSite", None)  # hapus jika tidak valid
    cookie.pop("expiry", None)  # hapus jika ada
    return cookie

options = webdriver.ChromeOptions()
# options.add_argument("--headless")  # Uncomment jika tidak perlu GUI
driver = webdriver.Chrome(options=options)

# Step 1: Buka domain dasar (harus sesuai domain cookie)
driver.get("https://mailh.qiye.163.com/")
time.sleep(2)

# Step 2: Inject cookies
with open("login163_cookies_2025-07-14_15-02-38.json", "r") as f:
    cookies = json.load(f)
    for cookie in cookies:
        try:
            fixed = fix_cookie(cookie)
            driver.add_cookie(fixed)
        except Exception as e:
            print(f"❌ Gagal inject cookie: {cookie.get('name')} => {e}")

# Step 3: Inject localStorage (opsional tapi penting)
with open("login163_localstorage_2025-07-14_15-02-38.json", "r", encoding="utf-8") as f:
    local_storage = json.load(f)
    for key, value in local_storage.items():
        # Gunakan JS string escape
        driver.execute_script(f"window.localStorage.setItem('{key}', `{value}`);")

time.sleep(1)

# Step 4: Akses halaman target langsung
driver.get("https://mailh.qiye.163.com/js6/main.jsp")
time.sleep(5)

# Step 5: Screenshot untuk konfirmasi
driver.save_screenshot("after_cookie_load.png")
print("✅ Cookie injection selesai. Screenshot disimpan.")

# (Opsional) Jangan tutup otomatis, agar bisa dilihat
input("Tekan Enter untuk keluar...")
driver.quit()
