import os
import subprocess
import sys


def get_repo_root():
    path = os.path.dirname(os.path.abspath(__file__))
    while path != os.path.dirname(path):
        if os.path.isdir(os.path.join(path, ".git")):
            return path
            
        path = os.path.dirname(path)

    return os.path.dirname(os.path.abspath(__file__))


def get_reload_file_path(repo_root):
    passenger = os.path.join(repo_root, "passenger_wsgi.py")
    if os.path.isfile(passenger):
        return passenger

    return os.path.join(repo_root, "app.py")


def run_deploy():
    repo_root = get_repo_root()
    reload_file = get_reload_file_path(repo_root)

    try:
        subprocess.run(
            ["git", "reset", "--hard"],
            cwd=repo_root,
            capture_output=True,
            text=True,
            timeout=30,
        )

        subprocess.run(
            ["git", "clean", "-fd"],
            cwd=repo_root,
            capture_output=True,
            text=True,
            timeout=30,
        )

        result = subprocess.run(
            [ "git", "pull" ],
            cwd=repo_root,
            capture_output=True,
            text=True,
            timeout=120,
        )
        output = (result.stdout or "").strip() + "\n" + (result.stderr or "").strip()
        if result.returncode != 0:
            return False, f"git pull failed: {output}"

        with open(reload_file, "a", encoding="utf-8"):
            os.utime(reload_file, None)
        tmp_dir = os.path.join(repo_root, "tmp")
        os.makedirs(tmp_dir, exist_ok=True)
        restart_txt = os.path.join(tmp_dir, "restart.txt")
        with open(restart_txt, "a", encoding="utf-8"):
            os.utime(restart_txt, None)

        return True, output or "OK"
    except subprocess.TimeoutExpired:
        return False, "git pull timed out"
    except Exception as error:
        return False, str(error)


if __name__ == "__main__":
    from app import create_app

    app = create_app()
    with app.app_context():
        success, message = run_deploy()

    if success:
        print(message)
        sys.exit(0)

    sys.exit(1)
