import urllib.request, json, os, urllib.parse

api_key = os.environ.get('YOUTUBE_API_KEY')
if not api_key and os.path.exists('.env'):
    for line in open('.env').readlines():
        if line.startswith('YOUTUBE_API_KEY='):
            api_key = line.strip().split('=', 1)[1].strip('\"\'')

if not api_key:
    # try secrets.env
    if os.path.exists('config/secrets.env'):
        for line in open('config/secrets.env').readlines():
            if line.startswith('YOUTUBE_API_KEY='):
                api_key = line.strip().split('=', 1)[1].strip('\"\'')

if not api_key:
    print('NO API KEY')
    exit()

channels = ['World of AI', 'IndyDevDan', 'All About AI', 'Anthropic', 'Prompt Engineering', 'Sam Witteveen']
for c in channels:
    url = f'https://www.googleapis.com/youtube/v3/search?part=snippet&q={urllib.parse.quote(c)}&type=channel&maxResults=1&key={api_key}'
    try:
        req = urllib.request.Request(url)
        with urllib.request.urlopen(req) as resp:
            data = json.loads(resp.read().decode())
            items = data.get('items', [])
            if items:
                print(f'{c} ID IS: {items[0]["id"]["channelId"]}')
            else:
                print(f'{c}: NO RESULTS')
    except Exception as e:
        print(f'{c}: ERR {e}')
