import os
import django
import requests
from datetime import datetime

# Setup Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from core.models import Lottery, DrawResult, AdminAccess

def restore_lotteries():
    lotteries_data = [
        ('mega_sena', 1, 60, 6),
        ('quina', 1, 80, 5),
        ('dupla_sena', 1, 50, 6),
        ('lotomania', 0, 99, 50),
        ('lotofacil', 1, 25, 15),
        ('timemania', 1, 80, 7),
        ('dia_de_sorte', 1, 31, 7),
        ('federal', 0, 99999, 5),
        ('super_sete', 0, 9, 7),
        ('maismilionaria', 1, 50, 6),
    ]
    
    for name, min_n, max_n, to_draw in lotteries_data:
        Lottery.objects.get_or_create(
            name=name,
            defaults={
                'min_number': min_n,
                'max_number': max_n,
                'numbers_to_draw': to_draw
            }
        )
    print("Loterias inicializadas.")

def restore_admin():
    if not AdminAccess.objects.exists():
        admin = AdminAccess.objects.create(private_key='admin123')
        print(f"Chave Admin criada: {admin.private_key}")
    else:
        print(f"Chave Admin existente: {AdminAccess.objects.first().private_key}")

def sync_all_latest():
    from core.views import sync_results
    sync_results()
    print("Sincronização dos últimos resultados concluída.")

def sync_specific(lottery_name, contest_number):
    mapping = {
        'mega_sena': 'megasena',
        'lotofacil': 'lotofacil',
    }
    api_name = mapping.get(lottery_name)
    if not api_name: return

    lottery = Lottery.objects.get(name=lottery_name)
    try:
        url = f"https://loteriascaixa-api.herokuapp.com/api/{api_name}/{contest_number}"
        response = requests.get(url, timeout=5)
        if response.status_code == 200:
            data = response.json()
            draw_number = int(data.get('concurso'))
            if not DrawResult.objects.filter(lottery=lottery, draw_number=draw_number).exists():
                date_str = data.get('data')
                draw_date = datetime.strptime(date_str, "%d/%m/%Y").date()
                numbers_list = data.get('dezenas', [])
                numbers_str = ",".join([str(int(n)) for n in numbers_list])
                DrawResult.objects.create(
                    lottery=lottery,
                    draw_number=draw_number,
                    draw_date=draw_date,
                    numbers=numbers_str
                )
                print(f"Sincronizado específico: {lottery_name} Concurso {draw_number}")
    except Exception as e:
        print(f"Erro ao sincronizar {lottery_name} {contest_number}: {e}")

if __name__ == "__main__":
    restore_lotteries()
    restore_admin()
    sync_all_latest()
    # Concursos solicitados na história
    for contest in [2976, 2977]:
        sync_specific('mega_sena', contest)
        sync_specific('lotofacil', contest)
    print("Restauração concluída!")
