import csv
import os

from eve_sde.models import Stargate

from .models import SolarSystemConnection, TrigInvasion


def regenerate_connections() -> None:
    SolarSystemConnection.objects.all().delete()

    connections = []

    for stargate in Stargate.objects.all():
        connections.append(SolarSystemConnection(
            fromsolarsystem=stargate.solar_system,
            tosolarsystem=stargate.destination,
            p_shortest=1,
            p_safest=1 if stargate.destination.security_status >= 0.45 else 50000.0,  # High Sec
            p_less_safe=1 if stargate.destination.security_status < 0.45 else 50000.0,  # Low/Null
        ))

    SolarSystemConnection.objects.bulk_create(connections, batch_size=500, ignore_conflicts=True)


def import_trig_data() -> None:
    TRIG_CSV_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'trigInvasionSystems.csv')
    trig_systems = []
    with open(TRIG_CSV_PATH, encoding='UTF-8') as f:
        csv_file = csv.reader(f)
        next(csv_file)  # skip headers
        for row in csv_file:
            trig_systems.append(TrigInvasion(
                system_id=row[0],
                status=row[1]
            ))

    TrigInvasion.objects.bulk_create(trig_systems, batch_size=500, ignore_conflicts=True)
