import asyncio
import os
import sys
import httpx
import json
import base64

# Gitea configuration
GITEA_API_URL = "https://git.reifonas.cloud/api/v1"
# Token found in app.ini
TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE3NzMxMDg3Mjl9.beKMVnmwBwdIyBhApfihXHMxvIMc3mXjJJQ0gLuwPAo"

async def fetch_from_gitea():
    url = f"{GITEA_API_URL}/repos/admtracksteel/Keys/contents/credentials.json"
    headers = {"Authorization": f"token {TOKEN}"}
    
    async with httpx.AsyncClient() as client:
        try:
            print(f"Buscando em {url}...")
            res = await client.get(url, headers=headers, timeout=20)
            if res.status_code == 200:
                content_b64 = res.json().get("content", "").replace("\n", "")
                data = json.loads(base64.b64decode(content_b64).decode())
                return data
            else:
                print(f"Erro Gitea: {res.status_code} - {res.text}")
        except Exception as e:
            print(f"Erro na requisição: {e}")
    return None

async def main():
    creds = await fetch_from_gitea()
    if creds:
        print("Credenciais recuperadas!")
        # Salva em um arquivo temporário
        with open("/root/Apps/BotVPS/.env.recovered", "w") as f:
            for k, v in creds.items():
                if isinstance(v, dict):
                    for subk, subv in v.items():
                        f.write(f"{subk.upper()}={subv}\n")
                else:
                    f.write(f"{k.upper()}={v}\n")
        print("Salvo em /root/Apps/BotVPS/.env.recovered")
    else:
        print("Não foi possível recuperar.")

if __name__ == "__main__":
    asyncio.run(main())
