import requests
import json
from urllib.parse import urlparse, parse_qs, urlencode

# First URL
url1 = "https://api.amemv.com/insights/lynx_web/anchor/preview?anchor_type=internet_service&app_id=1128&cmpt_version=1&component_id=7430558813054405430&download_style=1&interaction_style=1&is_preview=1&item_id=0&owner_id=1809047160845323&sec_uid=MS4wLjABAAAAHBDxS7uq2FpOE5kTjzuQTuIHOqL460dWJi9izIZedWIYRktaqewXWOw_rFvP8Avx"

# Parse URL parameters
parsed_url = urlparse(url1)
params = parse_qs(parsed_url.query)

# Extract required parameters
component_id = params['component_id'][0]
cmpt_version = params['cmpt_version'][0]
item_id = params['item_id'][0]
sec_uid = params['sec_uid'][0]
app_id = params['app_id'][0]

# Construct extra parameter
extra_data = {
    'item_id': item_id,
    'author_id': params['owner_id'][0],
    'device_platform': 'ios'
}

# Construct parameters for second URL
params2 = {
    'component_id': component_id,
    'cmpt_version': cmpt_version,
    'extra': json.dumps(extra_data),
    'app_id': app_id,
    'sec_uid': sec_uid
}

# Construct second URL
url2 = f"https://api.amemv.com/aweme/v1/saiyan/industry/component/anchor/page/?{urlencode(params2)}"

try:
    # Download content from second URL
    response = requests.get(url2, verify=False)
    response.raise_for_status()
    
    # Parse JSON response
    data = response.json()
    
    # Parse the data string inside anchor_page.data
    anchor_data = json.loads(data['anchor_page']['data'])
    
    # Extract and print specific fields from the first item
    if anchor_data and len(anchor_data) > 0:
        item = anchor_data[0]  # Get the first item
        print(f"wechat_microapp_jump_url: {item.get('wechat_microapp_jump_url', '')}")
        print(f"wechat_microapp_title: {item.get('wechat_microapp_title', '')}")
    
except requests.exceptions.RequestException as e:
    print(f"Error occurred: {e}")
except json.JSONDecodeError as e:
    print(f"JSON parsing error: {e}")