import requests
import json
from pprint import pprint
from typing import Union
import re
import pickle
import csv

cache = {}

def get_theme_info(anime_slug, theme_slug):
    if cache.get((anime_slug, theme_slug)):
        return cache.get((anime_slug, theme_slug))
    
    url_anime = f"https://api.animethemes.moe/anime/{anime_slug}?include=animethemes"

    anime_req = requests.get(url_anime)

    pprint((anime_slug, theme_slug))

    pprint(anime_req.json()['anime']['animethemes'])

    pprint(list(filter(lambda x : True if x['slug'] == theme_slug else False, anime_req.json()['anime']['animethemes'])))

    theme_id = list(filter(lambda x : True if x['type'] == theme_slug else False, anime_req.json()['anime']['animethemes']))[0]['id']

    url_theme = f"https://api.animethemes.moe/song/{theme_id}"

    theme_req = requests.get(url_theme)
    
    cache[(anime_slug, theme_slug)] = {"anime": anime_req.json()['anime']['name'], "title": theme_req.json()['song']['title'], "n_votes": 1}

    return {"anime": anime_req.json()['anime']['name'], "title": theme_req.json()['song']['title'], "n_votes": 1}


url_reg = re.compile("https://animethemes\.moe/anime/([a-z0-9_]*)/(OP|ED)([0-9]*)")

# https://animethemes.moe/anime/shingeki_no_kyojin_season_2/ED-NCBD1080
def url_to_info(url):
    match =  url_reg.match(url)

    return match.group(1), match.group(2)


# pprint(get_theme_info("ao_no_exorcist", "OP", 1))

# with open("datap", 'wb+') as f_out:
#     # vote_data = json.loads(f_out.readlines)

#     prev = pickle.load(f_out)

    for s in sorted(prev.items(), key=lambda x: x[1]['n_votes']):
        print(f"{s['anime']} - {s['title']} - {s['n_votes']}")

    # pprint(prev)

    # vote_data: dict[tuple[str, str], dict[str, Union[str, int]]] = {}

    # with open("votes.txt", 'r') as f:
    #     for n, line in enumerate(f.readlines()):
    #         print(f"########\n{n}")
    #         anime_slug, theme_slug = url_to_info(line)

    #         if vote_data.get((anime_slug, theme_slug)):
    #             vote_data[(anime_slug, theme_slug)]['n_votes'] += 1
    #         else:
    #             try:
    #                 vote_data[(anime_slug, theme_slug)] = get_theme_info(anime_slug, theme_slug)
    #             except:
    #                 pass

    # pickle.dump(vote_data, f_out)
    # # f_out.write(json.dumps(vote_data))
        
    # pprint(vote_data.items())
    # pprint(sorted(vote_data.items(), key=lambda x: x[1]['n_votes']))

    # pprint(vote_data)

# url = "https://api.animethemes.moe/anime"

# reqdata = {
#     "anime": {
#         "slug": "ao_no_exorcist"
#     }
# }

# req = requests.get(url, data=reqdata)

# pprint()



data = {('86', 'OP'): {'anime': '86', 'n_votes': 1, 'title': 'REVENGE'},
 ('ajin', 'OP'): {'anime': 'Ajin', 'n_votes': 1, 'title': 'Toumei na Yozora'},
 ('aku_no_hana', 'ED'): {'anime': 'Aku no Hana',
                         'n_votes': 1,
                         'title': 'Hana -a last flower-'},
 ('ansatsu_kyoushitsu_tv_2nd_season', 'OP'): {'anime': 'Ansatsu Kyoushitsu '
                                                       '(TV) 2nd Season',
                                              'n_votes': 1,
                                              'title': 'Page ~Kimi to Tsuzuru '
                                                       'Monogatari~'},
 ('ao_no_exorcist', 'OP'): {'anime': 'Ao no Exorcist',
                            'n_votes': 1,
                            'title': 'CORE PRIDE'},
 ('banana_fish', 'ED'): {'anime': 'Banana Fish',
                         'n_votes': 2,
                         'title': 'FREEDOM'},
 ('beastars_2nd_season', 'OP'): {'anime': 'Beastars 2nd Season',
                                 'n_votes': 1,
                                 'title': 'Sekai no Hate'},
 ('bishoujo_senshi_sailor_moon', 'OP'): {'anime': 'Bishoujo Senshi Sailor Moon',
                                         'n_votes': 1,
                                         'title': 'Moonlight Densetsu'},
 ('black_clover_tv', 'OP'): {'anime': 'Black Clover (TV)',
                             'n_votes': 1,
                             'title': 'Tenohira o Taiyou ni'},
 ('blackrock_shooter_tv', 'OP'): {'anime': 'Black★Rock Shooter (TV)',
                                  'n_votes': 1,
                                  'title': 'Black★Rock Shooter'},
 ('boku_dake_ga_inai_machi', 'OP'): {'anime': 'Boku dake ga Inai Machi',
                                     'n_votes': 2,
                                     'title': 'Kimi Toita Sora'},
 ('chainsaw_man', 'OP'): {'anime': 'Chainsaw Man',
                          'n_votes': 1,
                          'title': 'more<STRONGLY'},
 ('cowboy_bebop', 'OP'): {'anime': 'Cowboy Bebop',
                          'n_votes': 2,
                          'title': 'Tank!'},
 ('dead_mount_death_play', 'OP'): {'anime': 'Dead Mount Death Play',
                                   'n_votes': 1,
                                   'title': 'Continue Distortion'},
 ('death_parade', 'OP'): {'anime': 'Death Parade',
                          'n_votes': 2,
                          'title': 'Flyers'},
 ('domestic_na_kanojo', 'OP'): {'anime': 'Domestic na Kanojo',
                                'n_votes': 1,
                                'title': 'My Home'},
 ('dr_stone_stone_wars', 'OP'): {'anime': 'Dr. Stone: Stone Wars',
                                 'n_votes': 1,
                                 'title': 'Namae wo Yobu yo'},
 ('evangelion_30_you_can_not_redo', 'ED'): {'anime': 'Evangelion: 3.0 You Can '
                                                     '(Not) Redo',
                                            'n_votes': 1,
                                            'title': 'Sakura Nagashi'},
 ('fategrand_order_zettai_majuu_sensen_babylonia', 'OP'): {'anime': 'Fate/Grand '
                                                                    'Order: '
                                                                    'Zettai '
                                                                    'Majuu '
                                                                    'Sensen '
                                                                    'Babylonia',
                                                           'n_votes': 1,
                                                           'title': 'Stay '
                                                                    'Gold'},
 ('fatestay_night_movie_heavens_feel_iii_spring_song', 'ED'): {'anime': 'Fate/stay '
                                                                        'night '
                                                                        'Movie: '
                                                                        "Heaven's "
                                                                        'Feel '
                                                                        '- '
                                                                        'III. '
                                                                        'Spring '
                                                                        'Song',
                                                               'n_votes': 1,
                                                               'title': 'Pale '
                                                                        'Blue'},
 ('free', 'ED'): {'anime': 'Free!', 'n_votes': 1, 'title': 'SPLASH FREE'},
 ('fugou_keiji_balanceunlimited', 'OP'): {'anime': 'Fugou Keiji: '
                                                   'Balance:Unlimited',
                                          'n_votes': 1,
                                          'title': 'Eden'},
 ('fullmetal_alchemist', 'OP'): {'anime': 'Fullmetal Alchemist',
                                 'n_votes': 1,
                                 'title': 'Melissa'},
 ('fullmetal_alchemist_brotherhood', 'OP'): {'anime': 'Fullmetal Alchemist: '
                                                      'Brotherhood',
                                             'n_votes': 1,
                                             'title': 'again'},
 ('gakuen_alice', 'OP'): {'anime': 'Gakuen Alice',
                          'n_votes': 1,
                          'title': 'Pikapika no Taiyou'},
 ('jigokuraku', 'OP'): {'anime': 'Jigokuraku',
                        'n_votes': 1,
                        'title': 'Paradox'},
 ('jojo_no_kimyou_na_bouken', 'OP'): {'anime': 'JoJo no Kimyou na Bouken',
                                      'n_votes': 1,
                                      'title': 'JoJo ~Sono Chi no Sadame~'},
 ('jojo_no_kimyou_na_bouken_part_4_diamond_wa_kudakenai', 'OP'): {'anime': 'JoJo '
                                                                           'no '
                                                                           'Kimyou '
                                                                           'na '
                                                                           'Bouken '
                                                                           'Part '
                                                                           '4: '
                                                                           'Diamond '
                                                                           'wa '
                                                                           'Kudakenai',
                                                                  'n_votes': 3,
                                                                  'title': 'Crazy '
                                                                           'Noisy '
                                                                           'Bizarre '
                                                                           'Town'},
 ('kaguya_sama_wa_kokurasetai_tensai_tachi_no_renai_zunousen_2020', 'OP'): {'anime': 'Kaguya-sama '
                                                                                     'wa '
                                                                                     'Kokurasetai?: '
                                                                                     'Tensai-tachi '
                                                                                     'no '
                                                                                     'Renai '
                                                                                     'Zunousen',
                                                                            'n_votes': 1,
                                                                            'title': 'Anoko '
                                                                                     'ni '
                                                                                     'Drop '
                                                                                     'Kick'},
 ('kekkai_sensen', 'ED'): {'anime': 'Kekkai Sensen',
                           'n_votes': 1,
                           'title': 'Sugar Song to Bitter Step'},
 ('kimetsu_no_yaiba', 'OP'): {'anime': 'Kimetsu no Yaiba',
                              'n_votes': 1,
                              'title': 'Attouteki Vivid Days'},
 ('kimetsu_no_yaiba_yuukaku_hen', 'OP'): {'anime': 'Kimetsu no Yaiba: '
                                                   'Yuukaku-hen',
                                          'n_votes': 1,
                                          'title': 'Kibou ni Mukatte '
                                                   '~Shoutarou no Theme~'},
 ('kimi_no_na_wa', 'ED'): {'anime': 'Kimi no Na wa.',
                           'n_votes': 1,
                           'title': 'Nandemonaiya'},
 ('kuroshitsuji', 'OP'): {'anime': 'Kuroshitsuji',
                          'n_votes': 1,
                          'title': 'Monokuro No Kiss'},
 ('mahou_shoujo_madokamagica', 'ED'): {'anime': 'Mahou Shoujo Madoka★Magica',
                                       'n_votes': 1,
                                       'title': 'Mata Ashita'},
 ('mekakucity_actors', 'OP'): {'anime': 'Mekakucity Actors',
                               'n_votes': 1,
                               'title': 'daze'},
 ('mirai_nikki_redial', 'OP'): {'anime': 'Mirai Nikki Redial',
                                'n_votes': 1,
                                'title': 'Kyouki Chinden'},
 ('mobile_suit_gundam_iron_blooded_orphans', 'ED'): {'anime': 'Mobile Suit '
                                                              'Gundam: '
                                                              'Iron-Blooded '
                                                              'Orphans',
                                                     'n_votes': 1,
                                                     'title': 'Orphans no '
                                                              'Namida'},
 ('nana', 'OP'): {'anime': 'Nana', 'n_votes': 1, 'title': 'Rose'},
 ('naruto_shippuuden', 'OP'): {'anime': 'Naruto: Shippuuden',
                               'n_votes': 1,
                               'title': "Hero's Come Back"},
 ('neon_genesis_evangelion', 'OP'): {'anime': 'Neon Genesis Evangelion',
                                     'n_votes': 1,
                                     'title': 'Zankoku na Tenshi no Thesis'},
 ('noragami', 'OP'): {'anime': 'Noragami',
                      'n_votes': 2,
                      'title': 'Goya no Machiawase'},
 ('noragami_aragoto', 'OP'): {'anime': 'Noragami Aragoto',
                              'n_votes': 2,
                              'title': 'Kyouran Hey Kids!!'},
 ('one_piece', 'OP'): {'anime': 'One Piece', 'n_votes': 2, 'title': 'We Are!'},
 ('oshi_no_ko', 'OP'): {'anime': '"Oshi no Ko"', 'n_votes': 1, 'title': 'RAYS'},
 ('ouran_koukou_host_club', 'OP'): {'anime': 'Ouran Koukou Host Club',
                                    'n_votes': 2,
                                    'title': 'Sakura Kiss'},
 ('overlord_iii', 'OP'): {'anime': 'Overlord III',
                          'n_votes': 1,
                          'title': "'Suki' no Katachi"},
 ('paripi_koumei', 'OP'): {'anime': 'Paripi Koumei',
                           'n_votes': 1,
                           'title': 'Awesome!'},
 ('samurai_champloo', 'ED'): {'anime': 'Samurai Champloo',
                              'n_votes': 1,
                              'title': 'Shiki no Uta'},
 ('seishun_buta_yarou_wa_bunny_girl_senpai_no_yume_wo_minai', 'OP'): {'anime': 'Seishun '
                                                                               'Buta '
                                                                               'Yarou '
                                                                               'wa '
                                                                               'Bunny '
                                                                               'Girl '
                                                                               'Senpai '
                                                                               'no '
                                                                               'Yume '
                                                                               'wo '
                                                                               'Minai',
                                                                      'n_votes': 1,
                                                                      'title': 'Arasoi '
                                                                               'Shi '
                                                                               'ni '
                                                                               'Yuku '
                                                                               'Monotachi '
                                                                               'ni '
                                                                               'Shukufuku '
                                                                               'wo'},
 ('shingeki_no_kyojin', 'OP'): {'anime': 'Shingeki no Kyojin',
                                'n_votes': 1,
                                'title': 'Guren no Yumiya'},
 ('shingeki_no_kyojin_season_2', 'ED'): {'anime': 'Shingeki no Kyojin Season 2',
                                         'n_votes': 1,
                                         'title': 'Shinzou wo Sasageyo!'},
 ('shingeki_no_kyojin_season_3', 'OP'): {'anime': 'Shingeki no Kyojin Season 3',
                                         'n_votes': 1,
                                         'title': 'WALK'},
 ('shingeki_no_kyojin_the_final_season_part_2', 'ED'): {'anime': 'Shingeki no '
                                                                 'Kyojin: The '
                                                                 'Final Season '
                                                                 'Part 2',
                                                        'n_votes': 1,
                                                        'title': 'Special '
                                                                 'Force'},
 ('shingeki_no_kyojin_the_final_season_part_2', 'OP'): {'anime': 'Shingeki no '
                                                                 'Kyojin: The '
                                                                 'Final Season '
                                                                 'Part 2',
                                                        'n_votes': 1,
                                                        'title': 'Pianissimo'},
 ('shokugeki_no_souma_ni_no_sara', 'ED'): {'anime': 'Shokugeki no Souma: Ni no '
                                                    'Sara',
                                           'title': 'Snow Drop'},
 ('shokugeki_no_souma_san_no_sara', 'OP'): {'anime': 'Shokugeki no Souma: San '
                                                     'no Sara',
                                            'n_votes': 1,
                                            'title': 'Utsukushiki Zankoku na '
                                                     'Sekai'},
 ('soul_eater', 'OP'): {'anime': 'Soul Eater',
                        'n_votes': 1,
                        'title': 'Resonance'},
 ('tengen_toppa_gurren_lagann', 'OP'): {'anime': 'Tengen Toppa Gurren Lagann',
                                        'n_votes': 1,
                                        'title': 'Sorairo Days'},
 ('tokyo_ghoul', 'ED'): {'anime': 'Tokyo Ghoul',
                         'n_votes': 1,
                         'title': 'Seijatachi'},
 ('tokyo_ghoul', 'OP'): {'anime': 'Tokyo Ghoul',
                         'n_votes': 2,
                         'title': 'unravel'},
 ('tokyo_ghoulre', 'OP'): {'anime': 'Tokyo Ghoul:re',
                           'n_votes': 1,
                           'title': 'Renka Renbo'},
 ('uchuu_senkan_yamato_2199', 'OP'): {'anime': 'Uchuu Senkan Yamato 2199',
                                      'n_votes': 1,
                                      'title': 'Uchuu Senkan Yamato'},
 ('yakusoku_no_neverland', 'OP'): {'anime': 'Yakusoku no Neverland',
                                   'n_votes': 1,
                                   'title': 'Happy Happy Friends'}}

# for s in sorted(data.items(), key=lambda x: x['n_votes']):
#         print(f"{s['anime']} - {s['title']} - {s['n_votes']}")


with open('results.csv', 'w', encoding='utf-8') as file:
    writer = csv.writer(file)
    
    for s in data.items():
        try:
            writer.writerow([s[0][1], s[1]['anime'], s[1]['title'], s[1]['n_votes']])
        except:
            writer.writerow([s[0][1], s[1]['anime'], s[1]['title']])
    # try:
    #     print(f"{s[0][1]} - {s[1]['anime']} - {s[1]['title']} - {s[1]['n_votes']}")
    # except:
    #     print(f"FOUT {s[0][1]} - {s[1]['anime']} - {s[1]['title']}")
        # print(s[1])
        
    
        

        