import os
import subprocess
from datetime import datetime, timezone
from flask import Blueprint, jsonify, request, current_app

blueprint = Blueprint("health", __name__, url_prefix="/health")

REPO_ROOT = "/home/bianchin/public_html/app.prumoboard.com"
VENV_PIP = "/home/bianchin/virtualenv/public_html/app.prumoboard.com/3.13/bin/pip"
RESTART_FILE = os.path.join(REPO_ROOT, "tmp", "restart.txt")


@blueprint.get("/")
def health():
    return jsonify({"status": "ok", "service": "prumo", "timestamp": datetime.now(timezone.utc).isoformat()})


@blueprint.get("/ping")
def ping():
    return jsonify({"pong": True})


@blueprint.get("/hello")
def hello():
    return jsonify({"message": "Hello Prumo"})


@blueprint.post("/deploy")
def deploy():
    expected = current_app.config.get("DEPLOY_TOKEN")
    if not expected:
        return jsonify({"error": "deploy not configured"}), 503

    auth = request.headers.get("Authorization", "")
    if not auth.startswith("Bearer ") or auth[7:] != expected:
        return jsonify({"error": "unauthorized"}), 401

    def run(cmd, **kwargs):
        return subprocess.run(cmd, capture_output=True, text=True, **kwargs)

    fetch = run(["git", "fetch", "origin", "main"], cwd=REPO_ROOT)
    if fetch.returncode != 0:
        return jsonify({"error": "git fetch failed", "detail": fetch.stderr}), 500

    pull = run(["git", "reset", "--hard", "origin/main"], cwd=REPO_ROOT)
    if pull.returncode != 0:
        return jsonify({"error": "git reset failed", "detail": pull.stderr}), 500

    pip = run([VENV_PIP, "install", "--prefer-binary", "-q", "-r", "app/requirements.txt"], cwd=REPO_ROOT)
    if pip.returncode != 0:
        return jsonify({"error": "pip install failed", "detail": pip.stderr}), 500

    open(RESTART_FILE, "w").close()

    return jsonify({"ok": True, "pull": pull.stdout.strip()})
