# Název:  janssenpc_file_receive.py
# Verze:  1.0
# Datum:  2026-06-05
# Popis:  Stáhne soubory čekající na serveru (msgs.buzalka.cz) do ##JNJPrenos\ZHovorcovic\.
#         Spouštět ručně dle potřeby.

import base64
import hashlib
import requests
from pathlib import Path
from datetime import datetime
from cryptography.fernet import Fernet

TOKEN = "13e1bb01-9fd5-44a8-8ce9-4ee27133d340"
# POKUS: neutrální názvy endpointů, aby je JNJ proxy nepráskala podle klíčových slov.
# Server musí mít stejně přejmenované routy (/status, /item), jinak vrátí 404!
PENDING_URL = "https://msgs.buzalka.cz/status"
DOWNLOAD_URL = "https://msgs.buzalka.cz/item"
RECEIVE_DIR = Path(r"C:\Users\vbuzalka\OneDrive - JNJ\##JNJPrenos\ZHovorcovic")
LOG_FILE = Path(__file__).parent / "file_send.log"
_FERNET = Fernet(base64.urlsafe_b64encode(hashlib.sha256(TOKEN.encode()).digest()))


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


def resolve_dest(directory: Path, filename: str) -> Path:
    """Přepíše existující soubor, pokud je zamčený → name (2), (3)..."""
    dest = directory / filename
    if not dest.exists():
        return dest
    try:
        dest.open('r+b').close()
        return dest
    except PermissionError:
        pass
    stem = Path(filename).stem
    suffix = Path(filename).suffix
    n = 2
    while True:
        candidate = directory / f"{stem} ({n}){suffix}"
        if not candidate.exists():
            return candidate
        try:
            candidate.open('r+b').close()
            return candidate
        except PermissionError:
            n += 1


log("=== file_receive: Spuštění ===")

try:
    resp = requests.get(PENDING_URL, headers={"Authorization": f"Bearer {TOKEN}"}, timeout=30)
    resp.raise_for_status()
    pending = resp.json().get("files", [])
    log(f"Souborů čeká na serveru: {len(pending)}{' — ' + str(pending) if pending else ''}")
except Exception as e:
    log(f"CHYBA při dotazu na server: {e}")
    pending = []

if pending:
    RECEIVE_DIR.mkdir(parents=True, exist_ok=True)
    for filename in pending:
        try:
            r = requests.get(
                f"{DOWNLOAD_URL}/{filename}",
                headers={"Authorization": f"Bearer {TOKEN}"},
                timeout=120,
            )
            r.raise_for_status()
            decrypted = _FERNET.decrypt(r.content)
            dest = resolve_dest(RECEIVE_DIR, filename)
            dest.write_bytes(decrypted)
            log(f"  STAŽENO    | {filename}{' → ' + dest.name if dest.name != filename else ''}")
        except Exception as e:
            log(f"  CHYBA      | {filename} | {e}")

log("=== file_receive: Hotovo ===")
