# server.py
from flask import Flask, request, jsonify
import threading
import copytocandidates
from pathlib import Path
import json

app = Flask(__name__)

# يجب أن تكون نفس القيمة اللي في Zoho webhook
WEBHOOK_SECRET = "change_this_shared_secret"

# مجلد اللوج
LOG_DIR = Path("/var/www/zoho/Log")
LOG_DIR.mkdir(parents=True, exist_ok=True)
LOG_RECEIVED = LOG_DIR / "received_webhook.log"

def log_received_webhook(atsid, raw=None):
    entry = {"timestamp": copytocandidates._now(), "atsid": atsid}
    if raw:
        entry["raw"] = raw
    try:
        with open(LOG_RECEIVED, "a", encoding="utf-8") as f:
            f.write(json.dumps(entry, ensure_ascii=False) + "\n")
    except Exception as e:
        print("[LOG ERROR] Failed to write webhook log:", e)

@app.route("/zoho_webhook", methods=["GET", "POST"])
def zoho_webhook():
    # read secret and atsid from query/form or json
    atsid = request.args.get("atsid") or request.form.get("atsid")
    secret = request.args.get("secret") or request.form.get("secret")

    # also allow JSON body
    if not atsid and request.is_json:
        data = request.get_json(silent=True) or {}
        atsid = atsid or data.get("atsid")
        secret = secret or data.get("secret")

    if secret != WEBHOOK_SECRET:
        return jsonify({"status": "error", "message": "invalid secret"}), 403

    if not atsid:
        return jsonify({"status": "error", "message": "atsid not provided"}), 400

    # assemble raw payload for logging: combine args/form/json
    raw = {}
    try:
        raw.update(request.args.to_dict())
    except Exception:
        pass
    try:
        raw.update(request.form.to_dict())
    except Exception:
        pass
    if request.is_json:
        try:
            raw_json = request.get_json(silent=True) or {}
            if isinstance(raw_json, dict):
                raw.update(raw_json)
        except Exception:
            pass

    # سجل الـ atsID في اللوج
    log_received_webhook(atsid, raw)

    # start processing in background thread
    t = threading.Thread(target=copytocandidates.process_one_ats, args=(atsid,), daemon=True)
    t.start()

    return jsonify({"status": "accepted", "atsid": atsid}), 202

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5054, debug=False)
