# -*- coding: utf-8 -*-
"""
Napi automatikus futás — Rackforest cPanel cron-hoz.

Ezt hívja a cron minden hajnalban. Sorrendben:
  1. Napi adatok lekérése UNAS + Shoprenter API-bol (webshop_auto.py)
  2. Tételszintű márka-adat frisítése az előző napra (marka_lekerdezes.py)
  3. Dashboard újragenerálása az aldomain mappába (dashboard_export.py)

Célkonyvtar a config.py-bol jon: DASHBOARD_TARGET_DIR

Cron parancs (cPanel-ben):
  cd /home/USER/schneider-webshop-riport && /usr/bin/python3 napi_futas.py >> log/cron.log 2>&1
"""
import sys, os, subprocess, time
from datetime import datetime, timedelta

try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
LOG_DIR = os.path.join(SCRIPT_DIR, "log")
os.makedirs(LOG_DIR, exist_ok=True)

PYTHON = sys.executable  # Az aktualis Python ertelmezo

def log(msg):
    stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{stamp}] {msg}", flush=True)


def run(args, label):
    log(f"=== {label} START ===")
    log(f"    Parancs: {' '.join(args)}")
    t0 = time.time()
    try:
        r = subprocess.run(args, cwd=SCRIPT_DIR, capture_output=True, text=True,
                           encoding="utf-8", errors="replace", timeout=3600)
        # Az alszkript kimenete
        if r.stdout:
            for line in r.stdout.splitlines():
                print(f"    {line}", flush=True)
        if r.stderr:
            for line in r.stderr.splitlines():
                print(f"    [stderr] {line}", flush=True)
        ok = r.returncode == 0
    except subprocess.TimeoutExpired:
        log(f"!!! {label} timeout (1h)")
        return False
    except Exception as e:
        log(f"!!! {label} HIBA: {e}")
        return False
    dt = time.time() - t0
    log(f"=== {label} {'OK' if ok else 'HIBA'} ({dt:.1f}s) ===\n")
    return ok


def detect_target_dir():
    """A publikus dashboard mappa automatikus felismerese."""
    # 1) Config explicit ertek?
    try:
        from config import DASHBOARD_TARGET_DIR
        if DASHBOARD_TARGET_DIR and DASHBOARD_TARGET_DIR.strip():
            return DASHBOARD_TARGET_DIR.strip()
    except Exception:
        pass

    # 2) Default: ~/riport.schneider-juwelier.at (a user home alatt)
    candidates = [
        os.path.expanduser("~/riport.schneider-juwelier.at"),
        os.path.expanduser("~/public_html/riport.schneider-juwelier.at"),
        os.path.expanduser("~/public_html/riport"),
    ]
    for path in candidates:
        if os.path.isdir(path):
            return path

    # 3) Ha egyik sem letezik, az elsot adjuk vissza (a Python letrehozza)
    return candidates[0]


def main():
    log("########## NAPI FUTAS START ##########")
    target_dir = detect_target_dir()
    log(f"Dashboard celmappa: {target_dir}")

    # 1) Napi adatgyüjtés (UNAS + Shoprenter osszesen)
    ok = run([PYTHON, "webshop_auto.py"], "Napi adatgyujtes")
    if not ok:
        log("!!! Napi adatgyujtes hibaval vegzodott - folytatjuk a tobbi lepest")

    # 2) Tegnapi nap marka-szintu lekerdezese
    tegnap = (datetime.today() - timedelta(days=1)).strftime("%Y-%m-%d")
    run([PYTHON, "marka_lekerdezes.py", "--napi", tegnap], f"Marka lekerdezes ({tegnap})")

    # 3) Tegnapi nap utalvany-szintu lekerdezese.
    #    Auto-backfill: ha a napi_utalvany tabla meg ures vagy nagyon keves sor van,
    #    egyszeri visszamenoleges feltoltest futtatunk 2025-09-01-tol.
    needs_full_backfill = False
    try:
        import sqlite3
        c = sqlite3.connect(os.path.join(SCRIPT_DIR, "webshop_adatok.db"))
        try:
            n = c.execute("SELECT COUNT(*) FROM napi_utalvany").fetchone()[0]
        except sqlite3.OperationalError:
            n = 0
        c.close()
        if n < 50:
            needs_full_backfill = True
            log(f"[i] napi_utalvany tabla {n} sort tartalmaz -> teljes backfill futtatasa egyszer")
    except Exception as e:
        log(f"[!] Nem tudtam ellenorizni a napi_utalvany sorait: {e}")

    if needs_full_backfill:
        run([PYTHON, "utalvany_lekerdezes.py", "--quick-backfill", "2025-09-01"],
            "Utalvany TELJES backfill (2025-09-01-tol)")
    else:
        run([PYTHON, "utalvany_lekerdezes.py", "--quick-backfill", tegnap],
            f"Utalvany napi frissites ({tegnap}-tol)")

    # 4) Dashboard regeneralas + kihelyezes a webszerver mappajaba
    run([PYTHON, "dashboard_export.py", "--target-dir", target_dir], "Dashboard generalas")

    log("########## NAPI FUTAS END ##########\n")


if __name__ == "__main__":
    main()
