from flask import Flask, jsonify
import os
import requests

app = Flask(__name__)

PROXY_URL = os.environ.get(
    "PROXY_URL",
    "http://proxy:8080/fetch?url=http://treasure:5005/secret",
)
PUBLIC_URL = os.environ.get(
    "PUBLIC_URL",
    "http://proxy:8080/fetch?url=http://public:5006/status",
)
FLAG = os.environ.get("FLAG", "FLAG_NOT_SET")


def ssrf_still_open() -> bool:
    try:
        resp = requests.get(PROXY_URL, timeout=3)
        if resp.status_code == 200 and "INTERNAL_CHEST" in resp.text:
            return True
    except requests.exceptions.RequestException:
        return False
    return False


def public_access_ok() -> bool:
    try:
        resp = requests.get(PUBLIC_URL, timeout=3)
        if resp.status_code == 200 and "PUBLIC_OK" in resp.text:
            return True
    except requests.exceptions.RequestException:
        return False
    return False


@app.route("/get_flag", methods=["GET"])
def get_flag():
    if ssrf_still_open():
        return jsonify(
            {
                "status": "open",
                "message": "The crossroads still lets outsiders in. Patch the proxy.",
            }
        )
    if not public_access_ok():
        return jsonify(
            {
                "status": "blocked",
                "message": "Proxy blocks safe traffic. Allow public direction.",
            }
        )

    return jsonify({"status": "fixed", "flag": FLAG})


if __name__ == "__main__":
    port = int(os.environ.get("PORT", "9090"))
    app.run(host="0.0.0.0", port=port)
