import json
import base64
import time
import urllib.request
import subprocess
import os

def base64url_encode(data):
    return base64.urlsafe_b64encode(data).decode('utf-8').replace('=', '')

def get_drive_file_metadata(file_id):
    # Load credentials
    with open('/home/openclaw/.openclaw/workspace/google_service_account.json') as f:
        creds = json.load(f)
    
    private_key_str = creds['private_key']
    client_email = creds['client_email']
    token_uri = creds['token_uri']
    
    # JWT Header
    header = {"alg": "RS256", "typ": "JWT"}
    header_b64 = base64url_encode(json.dumps(header).encode())
    
    # JWT Payload
    now = int(time.time())
    payload = {
        "iss": client_email,
        "scope": "https://www.googleapis.com/auth/drive.readonly",
        "aud": token_uri,
        "iat": now,
        "exp": now + 3600
    }
    payload_b64 = base64url_encode(json.dumps(payload).encode())
    content = f"{header_b64}.{payload_b64}"
    
    key_file = '/tmp/priv_drive.pem'
    with open(key_file, 'w') as f:
        f.write(private_key_str)
    
    try:
        process = subprocess.Popen(
            ['openssl', 'dgst', '-sha256', '-sign', key_file],
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )
        signature, err = process.communicate(input=content.encode())
        if process.returncode != 0:
            raise Exception(f"OpenSSL error: {err.decode()}")
    finally:
        if os.path.exists(key_file):
            os.remove(key_file)
    
    signature_b64 = base64url_encode(signature)
    jwt = f"{content}.{signature_b64}"
    
    data = urllib.parse.urlencode({
        "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
        "assertion": jwt
    }).encode()
    
    req = urllib.request.Request(token_uri, data=data)
    with urllib.request.urlopen(req) as f:
        res = json.loads(f.read().decode())
    
    access_token = res['access_token']
    
    # Drive API Get Metadata
    # We also try to see if it's a file we can read
    url = f"https://www.googleapis.com/drive/v3/files/{file_id}?fields=name,mimeType"
    
    req = urllib.request.Request(url, headers={"Authorization": f"Bearer {access_token}"})
    try:
        with urllib.request.urlopen(req) as f:
            metadata = json.loads(f.read().decode())
        return metadata
    except urllib.error.HTTPError as e:
        return {"error": e.code, "body": e.read().decode()}

if __name__ == "__main__":
    file_id = "1zsVzSUTicnX4CWjgOp5Bj9cSXo7YuL9w"
    print(json.dumps(get_drive_file_metadata(file_id)))
