import os
import json
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# Scopes required for uploading videos to YouTube
SCOPES = ["https://www.googleapis.com/auth/youtube.upload"]
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE = os.path.join(SCRIPT_DIR, "social_config.json")

def main():
    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)

    yt_cfg = cfg.get("youtube", {})
    client_secrets = yt_cfg.get("client_secrets_file", "client_secrets.json")
    token_file = yt_cfg.get("token_file", "token.json")

    # Ensure paths are absolute relative to script dir
    if not os.path.isabs(client_secrets):
        client_secrets = os.path.join(SCRIPT_DIR, client_secrets)
    if not os.path.isabs(token_file):
        token_file = os.path.join(SCRIPT_DIR, token_file)

    if not os.path.exists(client_secrets):
        print(f"Error: {client_secrets} not found. Please download it from Google Cloud Console.")
        return

    creds = None
    if os.path.exists(token_file):
        creds = Credentials.from_authorized_user_file(token_file, SCOPES)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(client_secrets, SCOPES)
            # Run local server for auth. If on remote server, use console flow.
            # Using console flow as we are likely on a remote server.
            creds = flow.run_local_server(port=0)
            # If run_local_server fails, you might need to use flow.run_console() in older versions
            # or follow the link manually.
            
        with open(token_file, "w") as token:
            token.write(creds.to_json())
        print(f"Successfully saved credentials to {token_file}")
    else:
        print("Credentials are already valid.")

if __name__ == "__main__":
    main()
