import os
import time

import requests  # type: ignore

# Получить токен чтобы:
# https://oauth.vk.com/oauth/authorize?client_id=51534014&display=page&scope=photos,offline&response_type=token&v=5.131&slogin_h=4984535b54c59e09ca.f1e0b6dce0d0cc82e7&__q_hash=618f24fbac4bc34edbf09b8bc503e923
TOKEN = ""
VK_URL = "https://api.vk.com/method/"
headers = {"Authorization": f"Bearer {TOKEN}"}
postfix = "?v=5.131&state=123456"
group_id = 220240483
dir = "../assets/dog"
list_labels = [fname for fname in os.listdir(dir)]

r = requests.get(f"{VK_URL}photos.getAll{postfix}&access_token={TOKEN}&owner_id=-{group_id}&count=200")
if "error" in r.json():
    print("error", r.json())
    exit()
items = r.json().get("response").get("items")
names = {}
for item in items:
    if item.get("text") in names:
        print("Doubles: ", item.get("text"))
    names[item.get("text")] = True
for name in list_labels:
    if name.replace("_", " ") in names:
        print(f"Continue: {name}")
        continue
    if name in names:
        print(f"Continue: {name}")
        continue
    max_size = 0
    max_index = 0
    list_data = os.listdir(os.path.join(dir, name))
    for i, f in enumerate(list_data):
        file_stats = os.stat(os.path.join(dir, name, f))
        if file_stats.st_size > max_size:
            max_size = file_stats.st_size
            max_index = i
    image_name = list_data[max_index]
    file_stats = os.stat(os.path.join(dir, name, image_name))
    r = requests.post(
        f"{VK_URL}photos.createAlbum{postfix}",
        data={"title": name.replace("_", " "), "group_id": group_id},
        headers=headers,
    )
    if "error" in r.json():
        print("error", r.json())
        break
    album_id = r.json().get("response").get("id")
    r = requests.get(
        f"{VK_URL}photos.getUploadServer{postfix}&album_id={album_id}&access_token={TOKEN}&group_id={group_id}"
    )
    url = r.json().get("response").get("upload_url")
    files = {"file1": open(os.path.join(dir, name, image_name), "rb")}
    r = requests.post(url, files=files)
    server = r.json().get("server")
    photos_list = r.json().get("photos_list")
    hash_data = r.json().get("hash")
    aid = r.json().get("aid")
    r = requests.post(
        f"{VK_URL}photos.save{postfix}&hash={hash_data}",
        data={
            "album_id": aid,
            "server": server,
            "photos_list": photos_list,
            "caption": name.replace("_", " "),
            "group_id": group_id,
        },
        headers=headers,
    )
    if "error" in r.json():
        print("error", r.json())
        break
    print(f"Created: {name}")
    time.sleep(1)
