#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Orchestrator for all PRAVIDELNE scripts in exact order.
"""

import time, socket
for _ in range(30):
    try:
        socket.create_connection(("192.168.1.76", 3307), timeout=3).close()
        break
    except OSError:
        time.sleep(10)

import sys
import subprocess
from pathlib import Path
from datetime import datetime

# =====================================================================
# Import EXACT Functions.py from:  C:\Reporting\Fio\Functions.py
# This bypasses all other Functions.py files in the system.
# =====================================================================

import importlib.util

FUNCTIONS_FILE = Path(r"C:\Reporting\Fio\Functions.py")

spec = importlib.util.spec_from_file_location("Functions_FIO", FUNCTIONS_FILE)
Functions_FIO = importlib.util.module_from_spec(spec)
sys.modules["Functions_FIO"] = Functions_FIO
spec.loader.exec_module(Functions_FIO)

# correct WhatsApp function
SendWhatsAppMessage = Functions_FIO.SendWhatsAppMessage


# =====================================================================
# General Orchestrator Settings
# =====================================================================

# folder where orchestrator + sub-scripts live
BASE_DIR = Path(__file__).resolve().parent

SCRIPTS_IN_ORDER = [
    "PRAVIDELNE_0_READ_ALL_ACTIVE_POZADAVKY.py",
    "PRAVIDELNE_1_ReadLast300DonePozadavku.py",
    "PRAVIDELNE_2_ReadPoznamky.py",
    "PRAVIDELNE_3_StahniKomunikaci.py",
    "PRAVIDELNE_4_StahniPrilohyUlozDoMySQL.py",
    "PRAVIDELNE_5_SaveToFileSystem incremental.py",
]

LOG_FILE = BASE_DIR / "PRAVIDELNE_log.txt"


# =====================================================================
# Logging + WhatsApp wrappers
# =====================================================================

def log(msg: str):
    ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    line = f"[{ts}] {msg}"
    print(line)
    try:
        with LOG_FILE.open("a", encoding="utf-8") as f:
            f.write(line + "\n")
    except:
        pass


def whatsapp_notify(text: str):
    """WhatsApp message wrapper — never allowed to crash orchestrator"""
    try:
        SendWhatsAppMessage(text)
    except:
        pass


# =====================================================================
# Main orchestrator
# =====================================================================

def main():
    log("=== START pravidelného běhu ===")
    whatsapp_notify("🏁 *PRAVIDELNÉ skripty: START*")

    for script_name in SCRIPTS_IN_ORDER:
        script_path = BASE_DIR / script_name

        if not script_path.exists():
            err = f"❌ Skript nenalezen: {script_path}"
            log(err)
            whatsapp_notify(err)
            continue

        log(f"▶ Spouštím: {script_path.name}")
        whatsapp_notify(f"▶ *Spouštím:* {script_path.name}")

        try:
            result = subprocess.run(
                [sys.executable, str(script_path)],
                cwd=str(BASE_DIR),
                capture_output=True,
                text=True,
                encoding="utf-8",
                errors="ignore",
            )
        except Exception as e:
            err = f"💥 Chyba při spouštění {script_path.name}: {e}"
            log(err)
            whatsapp_notify(err)
            continue

        # return code
        rc_msg = f"↳ {script_path.name} return code: {result.returncode}"
        log(rc_msg)
        whatsapp_notify(rc_msg)

        # stderr (warnings/errors)
        if result.stderr:
            err_msg = f"⚠ stderr v {script_path.name}:\n{result.stderr.strip()}"
            log(err_msg)
            whatsapp_notify(err_msg)

    log("=== KONEC pravidelného běhu ===")
    whatsapp_notify("✅ *PRAVIDELNÉ skripty: KONEC*\n")


# =====================================================================
# Entry point
# =====================================================================

if __name__ == "__main__":
    main()
