# Gateway RAR AUTOPASS — un container API + un container worker, acelasi image,
# acelasi volum SQLite persistent (plan.md sect. 4 + 9). restart: always pe ambele.
#
# CRITIC: AUTOPASS_CREDS_KEY trebuie PARTAJATA intre api si worker — API cripteaza
# creds-urile RAR, worker-ul le decripteaza. Chei diferite -> worker nu poate
# decripta -> submission-uri blocate "creds indisponibile". Seteaz-o in .env
# (vezi .env.example): compose o citeste automat. Lipsa -> compose pica explicit.
services:
  api:
    build: .
    command: uvicorn app.main:app --host 0.0.0.0 --port 8010
    volumes:
      - autopass-data:/data
    environment:
      AUTOPASS_DB_PATH: /data/autopass.db
      # Ancora globala, NU tinta trimiterilor: mediul RAR e per
      # submission/cont (worker-ul trimite dupa submissions.rar_env). Variabila
      # asta serveste doar ca fallback API pentru conturi fara medii disponibile,
      # backfill la migrare (db.py) si afisaj dashboard (routes.py). Obligatorie
      # ca sa nu difere tacit intre api si worker (vezi worker mai jos).
      AUTOPASS_RAR_ENV: ${AUTOPASS_RAR_ENV:?seteaza AUTOPASS_RAR_ENV (test|prod) in .env (vezi .env.example)}
      # Fus orar RO pentru bucketarea contoarelor azi/luna (SQLite 'localtime', E7).
      TZ: ${TZ:-Europe/Bucharest}
      AUTOPASS_CREDS_KEY: ${AUTOPASS_CREDS_KEY:?seteaza AUTOPASS_CREDS_KEY in .env (vezi .env.example)}
      AUTOPASS_REQUIRE_API_KEY: ${AUTOPASS_REQUIRE_API_KEY:?seteaza AUTOPASS_REQUIRE_API_KEY (true in prod) in .env (vezi .env.example)}
      # Embeddings (sugestie mapare, Stratul 2): prima cerere /mapari lazy-load-eaza
      # modelul ~230MB. Doar API-ul il incarca (worker-ul nu). Default off.
      AUTOPASS_EMBEDDINGS_ENABLED: ${AUTOPASS_EMBEDDINGS_ENABLED:-false}
      # uvicorn 0.30.0 are proxy_headers=True implicit; lipsea doar increderea in
      # sursa headerelor, altfel request.client.host = IP-ul Traefik pentru toti
      # vizitatorii (rate-limit login/signup devine o galeata GLOBALA). Uvicorn
      # citeste FORWARDED_ALLOW_IPS direct din mediu (fara flag CLI necesar).
      # ATENTIE, doua invariante trebuie sa ramana adevarate impreuna cu "*":
      #  (1) serviciul api NU publica `ports:` pe host aici — accesibil DOAR prin Traefik;
      #  (2) Traefik NU e configurat cu forwardedHeaders.insecure=true.
      # Daca (2) e incalcat, un atacator poate falsifica X-Forwarded-For si ocoli
      # rate-limit-ul (galeata noua per cerere = brute-force nelimitat).
      FORWARDED_ALLOW_IPS: "*"
      # Fara secret persistent, fiecare redeploy delogheaza toti userii (main.py
      # genereaza unul efemer la runtime). HTTPS_ONLY=true e corect pentru prod,
      # dar inseamna ca un smoke-test simplu pe HTTP NU poate face login (browserul
      # dropeaza cookie-ul Secure) — pe HTTP local seteaza explicit false.
      AUTOPASS_SESSION_SECRET: ${AUTOPASS_SESSION_SECRET:?seteaza AUTOPASS_SESSION_SECRET in .env (vezi .env.example)}
      AUTOPASS_SESSION_HTTPS_ONLY: ${AUTOPASS_SESSION_HTTPS_ONLY:-true}
    restart: always
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8010/healthz').status==200 else 1)"]
      interval: 30s
      timeout: 5s
      retries: 3

  worker:
    build: .
    command: python -m app.worker
    volumes:
      - autopass-data:/data
    environment:
      AUTOPASS_DB_PATH: /data/autopass.db
      # Vezi comentariul de la serviciul api: ancora globala, NU tinta trimiterilor
      # (worker-ul trimite dupa submissions.rar_env, per cont). Aceeasi variabila
      # obligatorie AICI, ca sa nu diverga tacit fata de api (era prod/test split-brain).
      AUTOPASS_RAR_ENV: ${AUTOPASS_RAR_ENV:?seteaza AUTOPASS_RAR_ENV (test|prod) in .env (vezi .env.example)}
      AUTOPASS_CREDS_KEY: ${AUTOPASS_CREDS_KEY:?seteaza AUTOPASS_CREDS_KEY in .env (vezi .env.example)}
      # Send catre RAR. Obligatoriu explicit — fara ea, un misconfig ar putea lasa
      # worker-ul sa trimita declaratii reale neintentionat (Legea 142/2023).
      # false = nu trimite (sigur pentru probe). true = end-to-end.
      AUTOPASS_WORKER_SEND_ENABLED: ${AUTOPASS_WORKER_SEND_ENABLED:?seteaza AUTOPASS_WORKER_SEND_ENABLED (true|false) in .env (vezi .env.example)}
    restart: always
    depends_on:
      - api
    # T6: probe pe heartbeat-ul din DB — prinde worker-ul AGATAT (proces viu, beat
    # invechit), pe care restart:always singur nu-l vede. start_period acopera bootul.
    # ATENTIE: in compose simplu, "unhealthy" doar marcheaza containerul — NU il
    # restarteaza (restart:always reactioneaza la EXIT). Sidecar-ul `autoheal` de
    # mai jos vede label-ul si chiar restarteaza worker-ul cand pica probe-ul.
    labels:
      autoheal: "true"
    healthcheck:
      test: ["CMD", "python", "-m", "app.worker.healthcheck"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 30s

  # Restarteaza orice container marcat unhealthy cu label autoheal=true (worker-ul
  # agatat). Alternativa: Docker Swarm (restart on unhealthy nativ).
  autoheal:
    image: willfarrell/autoheal:latest
    restart: always
    environment:
      AUTOHEAL_CONTAINER_LABEL: autoheal
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

  # Backup SQLite criptat (T2/P0-4, evidenta legala L.142/2023) — vezi docs/backup.md.
  # Serviciu OPTIONAL, profil "backup": nu porneste la `docker compose up` normal.
  # Activare: `docker compose --profile backup up -d backup` (sau COMPOSE_PROFILES=backup
  # in mediul Dokploy). Alternativa fara profil compose: cron pe host care ruleaza
  # `docker compose exec api bash tools/backup_db.sh` — mai simpla daca ai deja acces SSH
  # la host, dar in Dokploy hostul poate fi gestionat/efemer, de aceea preferam varianta
  # de mai jos (calatoreste cu image-ul, nu depinde de un cron configurat manual pe VM).
  # backup:
  #   build: .
  #   profiles: ["backup"]
  #   entrypoint: ["bash", "-c"]
  #   command:
  #     - |
  #       while true; do
  #         bash tools/backup_db.sh || echo "[backup] rulare esuata, reincerc la urmatorul ciclu"
  #         sleep 86400
  #       done
  #   volumes:
  #     - autopass-data:/data
  #   environment:
  #     AUTOPASS_DB_PATH: /data/autopass.db
  #     AUTOPASS_BACKUP_DIR: ${AUTOPASS_BACKUP_DIR:-/data/backups}
  #     AUTOPASS_BACKUP_KEEP: ${AUTOPASS_BACKUP_KEEP:-14}
  #     AUTOPASS_BACKUP_PASSPHRASE_FILE: ${AUTOPASS_BACKUP_PASSPHRASE_FILE:-}
  #     AUTOPASS_BACKUP_PASSPHRASE: ${AUTOPASS_BACKUP_PASSPHRASE:-}
  #     AUTOPASS_BACKUP_RCLONE_REMOTE: ${AUTOPASS_BACKUP_RCLONE_REMOTE:-}
  #   restart: always

volumes:
  autopass-data:
