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

import os
import sys
import subprocess
import time
from datetime import datetime

import sys
import io

# Force UTF-8 output for Scheduled Tasks
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')


BASE_DIR = os.path.dirname(os.path.abspath(__file__))

SCRIPT1 = os.path.join(BASE_DIR, "21ReadJSONmultipleaccounts.py")
SCRIPT2 = os.path.join(BASE_DIR, "30Report.py")
LOG_DIR = os.path.join(BASE_DIR, "logs")
LOG_FILE = os.path.join(LOG_DIR, "FIOreport.log")

os.makedirs(LOG_DIR, exist_ok=True)

# Optional WhatsApp notify
try:
    from Functions import SendWhatsAppMessage
    WHATSAPP_AVAILABLE = True
except Exception:
    WHATSAPP_AVAILABLE = False


def write_log(text):
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        f.write(text + "\n")
    print(text)


def run_script(path):
    write_log(f"\n[{datetime.now()}] ➡ Running: {os.path.basename(path)}")

    if not os.path.isfile(path):
        write_log(f"❌ Script not found: {path}")
        return False

    process = subprocess.Popen(
        [sys.executable, path],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        encoding="utf-8",
        errors="replace"
    )

    # Log STDOUT live
    for line in process.stdout:
        write_log(line.rstrip())

    # Log STDERR live
    for line in process.stderr:
        write_log("⚠️ " + line.rstrip())

    process.wait()
    return process.returncode == 0


# ----------------------------------------------------------
# MAIN
# ----------------------------------------------------------
if __name__ == "__main__":
    write_log("\n====================== NEW RUN ======================")

    ok1 = run_script(SCRIPT1)
    ok2 = False

    if ok1:
        write_log("✔ Stage 1 OK")
        time.sleep(1)
        ok2 = run_script(SCRIPT2)

    if ok1 and ok2:
        write_log("✔ All stages completed successfully")
        if WHATSAPP_AVAILABLE:
            SendWhatsAppMessage("✔ FIO import + report hotový.")
    else:
        write_log("❌ SOME PART FAILED — check above for errors")
        if WHATSAPP_AVAILABLE:
            SendWhatsAppMessage("❌ FIO proces selhal. Zkontroluj log.")

    write_log("======================== END ========================\n")
