import time
from datetime import datetime, timedelta
from pathlib import Path

import typer


def main(filename: str, tolerance: int = 12, duration: int = 6):
    now_ts = datetime.now()
    max_ts = now_ts + timedelta(hours=duration)
    file_mtime_ts = datetime.fromtimestamp(Path(filename).stat().st_mtime)

    print(f"Warte auf Datei {filename}")
    print("Aktuelle Uhrzeit:   " + now_ts.strftime("%d.%m.%Y %H:%M:%S"))
    print("Aenderungsdatum:    " + file_mtime_ts.strftime("%d.%m.%Y %H:%M:%S"))
    print("Maximale Wartezeit: " + max_ts.strftime("%d.%m.%Y %H:%M:%S"))
    print("")

    while now_ts < max_ts:
        now_ts = datetime.now()
        file_mtime_ts = datetime.fromtimestamp(Path(filename).stat().st_mtime)

        oldest_ts = now_ts - timedelta(hours=tolerance)
        newest_ts = now_ts - timedelta(minutes=10)

        if file_mtime_ts >= oldest_ts and file_mtime_ts <= newest_ts:
            print(f"\nDatei {filename} ist bereit")
            return
        print(".", end="")
        time.sleep(60)
    print(f"\n!! Datei {filename} ist nicht aktuell. Warten beendet !!")
    exit(1)


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