import json
import os
import threading
import time
from datetime import datetime

from flask import Flask, jsonify, request

from m365_bypass import BypassEngine, OUTPUT_DIR, _format_netscape

app = Flask(__name__, static_folder="static", static_url_path="")

JOBS = {}
_JOBS_LOCK = threading.Lock()
_SEQ_LOCK = threading.Lock()
_SEQ = 0
_MAX_LOGS = 1000


def _new_job():
    global _SEQ
    with _SEQ_LOCK:
        _SEQ += 1
        job_id = f"job_{_SEQ}_{int(time.time() * 1000)}"
    JOBS[job_id] = {
        "job_id": job_id,
        "status": "queued",
        "email": None,
        "progress": {"value": 0, "text": "Queued"},
        "logs": [],
        "result": None,
        "error": None,
        "created_at": datetime.now().isoformat(),
    }
    return job_id


def _append_log(job_id, msg, tag="INFO"):
    with _JOBS_LOCK:
        job = JOBS.get(job_id)
        if not job:
            return
        logs = job.setdefault("logs", [])
        logs.append({"time": datetime.now().strftime("%H:%M:%S"), "tag": tag, "msg": msg})
        if len(logs) > _MAX_LOGS:
            del logs[: len(logs) - _MAX_LOGS]


def _run_job(job_id, email, password, app_id):
    def log_cb(msg, tag="INFO"):
        _append_log(job_id, msg, tag)

    def prog_cb(value, text=""):
        with _JOBS_LOCK:
            job = JOBS.get(job_id)
            if job:
                job["progress"] = {"value": value, "text": text}

    engine = BypassEngine(log=log_cb, prog=prog_cb)
    if app_id:
        engine.config["app_ids"] = [{"id": app_id, "name": "Manual"}]
    result = engine.run(email, password)

    with _JOBS_LOCK:
        job = JOBS.get(job_id)
        if job is None:
            return
        job["progress"] = {"value": 100, "text": "DONE"}

    if result is False:
        with _JOBS_LOCK:
            job = JOBS.get(job_id)
            if job is not None:
                job["status"] = "failed"
                job["error"] = "bypass_failed"
        return

    cookie_path, has_ests = result
    cookies = []
    if cookie_path and os.path.exists(cookie_path):
        try:
            with open(cookie_path, "r") as f:
                cookies = json.load(f)
        except Exception:
            cookies = []

    payload = {
        "ok": True,
        "email": email,
        "cookies": cookies,
        "cookies_netscape": _format_netscape(cookies),
        "cookie_file": cookie_path,
        "has_ests": bool(has_ests),
    }
    with _JOBS_LOCK:
        job = JOBS.get(job_id)
        if job is not None:
            job["status"] = "completed"
            job["result"] = payload


@app.route("/api/health", methods=["GET"])
def health():
    return jsonify({"ok": True, "service": "office365-m365-bypass", "status": "running"})


@app.route("/api/bypass", methods=["POST"])
def bypass():
    data = request.get_json(silent=True)
    if data is None:
        data = request.form.to_dict()
    email = str(data.get("email") or "").strip()
    password = str(data.get("password") or "").strip()
    app_id = str(data.get("app_id") or "").strip() or None
    if not email or not password:
        return (
            jsonify({"ok": False, "error": "email_required", "message": "email and password are required"}),
            400,
        )
    job_id = _new_job()
    t = threading.Thread(target=_run_job, args=(job_id, email, password, app_id), daemon=True)
    t.start()
    return jsonify({"ok": True, "job_id": job_id, "status": "queued"})


@app.route("/api/status/<job_id>", methods=["GET"])
def status(job_id):
    with _JOBS_LOCK:
        job = JOBS.get(job_id)
    if not job:
        return jsonify({"ok": False, "error": "job_not_found"}), 404
    resp = dict(job)
    resp["logs"] = list(job.get("logs") or [])
    return jsonify(resp)


@app.route("/")
def index():
    return app.send_static_file("index.html")


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=False)
