#!/usr/bin/env python3
import json
import requests
import os
import sys

# Configuration
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE = os.path.join(SCRIPT_DIR, "social_config.json")

def exchange_code_for_token(auth_code):
    if not os.path.exists(CONFIG_FILE):
        print(f"Error: {CONFIG_FILE} not found.")
        return

    with open(CONFIG_FILE, "r") as f:
        cfg = json.load(f)

    tt_cfg = cfg.get("tiktok", {})
    client_key = tt_cfg.get("client_key")
    client_secret = tt_cfg.get("client_secret")
    
    if not client_key or not client_secret:
        print("Error: TikTok client_key or client_secret not found in social_config.json")
        return

    # Redirect URI must match the one used to get the code
    redirect_uri = "https://learn-lexicore.bytronex.com/auth/callback"
    
    token_url = "https://open.tiktokapis.com/v2/oauth/token/"
    headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }
    
    data = {
        "client_key": client_key,
        "client_secret": client_secret,
        "code": auth_code,
        "grant_type": "authorization_code",
        "redirect_uri": redirect_uri
    }
    
    print(f"Exchanging code for token...")
    resp = requests.post(token_url, data=data, headers=headers)
    
    if resp.status_code == 200:
        res_data = resp.json()
        if "access_token" in res_data:
            access_token = res_data["access_token"]
            open_id = res_data["open_id"]
            
            # Update config
            cfg["tiktok"]["access_token"] = access_token
            cfg["tiktok"]["open_id"] = open_id
            
            with open(CONFIG_FILE, "w") as f:
                json.dump(cfg, f, indent=4, ensure_ascii=False)
            
            print("✅ Successfully updated social_config.json with TikTok access_token and open_id")
        else:
            print(f"❌ Error in response data: {res_data}")
    else:
        print(f"❌ Failed to exchange code: {resp.status_code} - {resp.text}")

if __name__ == "__main__":
    if len(sys.argv) > 1:
        code = sys.argv[1]
    else:
        # If no arg, could ask or hardcode if we know it
        # The user provided: bHjvaamS-9slItxe34qzaE0ji5yR7W3DsMvyHSM80AogA4S83ALCy9Ev21mZYPoXD-wxx0tcw363SlYwBPse9PLBBzTaQakbmBMHXhqSHAzKxPSSoCCIAzkLrn6DXleHuVYIWJYnwaZazWLAO-5VEXC9nR_K6zVK5Zg7759qC7__rx49glGw3H-kV8R8OtlGiFuGxgDiZ2O1PPyzNMO4l0frSmToCPD_hKe5i-MDiJe5G_1wLqzPs-nAHCw%2Av%215205.e1
        # It's better to pass it as an argument
        print("Usage: python3 finalize_tt_auth.py <code>")
        sys.exit(1)
        
    exchange_code_for_token(code)
