import os
import base64
from datetime import datetime
from app.libraries.database import Database
from app.libraries.forgejo import Forgejo, ForgejoNotFoundError
import pdb

def date_string():

    now = datetime.now()

    day = '{:02d}'.format(now.day)

    month = '{:02d}'.format(now.month)

    year = str(now.year)[2:]

    return f'{year}{month}{day}'

if __name__ == '__main__':

    db = Database()

    if not os.path.exists('dataset'):

        os.makedirs('dataset')

    date = date_string()

    if not os.path.exists(f'dataset/{date}'):

        os.makedirs(f'dataset/{date}')

    filename = f'dataset_{date}.csv'

    db.csv_save(f'dataset/{date}/{filename}')

    fgj = Forgejo()

    gituser = fgj.user()

    try:

        with open(f'dataset/{date}/{filename}', 'rb') as input_file:
            data = input_file.read()
            file = base64.b64encode(data)

        response = fgj.repo_owner_create_file(gituser.login, fgj.stats_repo, f'dataset/{date}/{filename}', gituser.email, gituser.login, "main", file, f"{date} fediverse's dataset")

        if 'content' in response:

            print(f'{filename} uploaded to {fgj.api_base_url}/{gituser.login}/{fgj.stats_repo}')

    except:

        print(response)

        pass
