import schedule
import time
import subprocess
import datetime
import os
import psutil
from dotenv import load_dotenv

load_dotenv()

MAIN_DIR = os.getcwd()
LOG_DIR = os.path.join(MAIN_DIR, 'Logs')
os.makedirs(LOG_DIR, exist_ok=True)

logfile_path = os.path.join(LOG_DIR, f"main_schedule_log_{datetime.datetime.now().strftime('%Y-%m-%d')}.txt")

def write_log(line):
    """Schreibt eine Zeile mit aktuellem Zeitstempel ins Logfile"""
    timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    log_entry = f"[{timestamp}] {line}"
    print(log_entry)
    with open(logfile_path, 'a', encoding='utf-8') as f:
        f.write(log_entry + '\n' + '-' * 60 + '\n')


def kill_existing_process(name):
    """Beendet alle laufenden Prozesse mit passendem Namen (case-insensitive, mit/ohne .exe)"""
    killed = False
    base_name = name.lower().replace('.exe', '')
    for proc in psutil.process_iter(['name']):
        try:
            pname = proc.info['name'].lower().replace('.exe', '')
            if pname == base_name:
                proc.kill()
                killed = True
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            pass
    return killed


def run_exe(name):
    """Startet eine EXE und loggt Erfolg/Fehler"""
    write_log(f"Starte {name}...")

    if kill_existing_process(name):
        write_log(f"Vorherige Instanz von {name} wurde beendet.")

    try:
        result = subprocess.run([name], capture_output=True, text=True, check=False)
        if result.returncode != 0:
            write_log(f"Fehler bei {name}: {result.stderr.strip()}")
        else:
            output = result.stdout.strip()
            if output:
                write_log(f"{name} erfolgreich: {output}")
            else:
                write_log(f"{name} erfolgreich beendet (kein Output).")
    except FileNotFoundError:
        write_log(f"Fehler: {name} wurde nicht gefunden!")
    except Exception as e:
        write_log(f"Unerwarteter Fehler bei {name}: {e}")


# Konfiguration
exporter_time = int(os.getenv('EXPORTER_TIME', '10'))  # Minuten
importer_time_of_day = os.getenv('IMPORTER_TIME_OF_DAY', '23:30')

# Tasks registrieren
schedule.every(exporter_time).minutes.do(lambda: run_exe('exporter.exe'))
schedule.every().day.at(importer_time_of_day).do(lambda: run_exe('importer.exe'))

# Startmeldung
write_log("Starte Task-Scheduler...")
write_log(f"SDF - Export-Intervall: alle {exporter_time} Minuten")
write_log(f"SDF - Import-Zeit: {importer_time_of_day}")

# Endlosschleife
while True:
    schedule.run_pending()
    time.sleep(10)
