from flask import Flask, render_template, request
from urllib.parse import urlparse
import ipaddress
import requests
import socket
import os

app = Flask(__name__)

MAX_OUTPUT = 5000
CHECKER_URL = os.environ.get("CHECKER_URL", "http://checker:9090/get_flag")
PUBLIC_HOST_ALLOWLIST = {"public"}


def is_safe_url(url: str) -> bool:
    # БЛОК ДЛЯ РЕДАКТИРОВАНИЯ:
        return True
    # КОНЕЦ БЛОКА ДЛЯ РЕДАКТИРОВАНИЯ

def fetch_url(url: str):
    try:
        response = requests.get(url, timeout=2, allow_redirects=True)
        text = response.text
        if len(text) > MAX_OUTPUT:
            text = text[:MAX_OUTPUT] + "\n... (truncated)"
        return True, text, response.status_code
    except requests.exceptions.RequestException as exc:
        return False, f"Request failed: {exc}", 502


@app.route("/", methods=["GET"])
def index():
    return render_template("index.html")


@app.route("/fetch", methods=["GET", "POST"])
def fetch():
    url = request.values.get("url", "").strip()
    if not url:
        return render_template("index.html", error="Enter a URL."), 400

    if not is_safe_url(url):
        return render_template("index.html", error="This direction is blocked by the village guard."), 400

    ok, data, status = fetch_url(url)
    if not ok:
        return render_template("index.html", error=data), status

    return render_template("index.html", result=data, status=status, url=url)


@app.route("/flag", methods=["GET"])
def flag():
    try:
        resp = requests.get(CHECKER_URL, timeout=3)
        data = resp.json()
        if data.get("status") == "fixed" and data.get("flag"):
            return render_template(
                "index.html",
                flag=data.get("flag"),
                flag_status="fixed",
            )
        return render_template(
            "index.html",
            error="Flag is not available yet. The checker still sees VULN open.",
            flag_status=data.get("status", "unknown"),
        )
    except requests.exceptions.RequestException as exc:
        return render_template("index.html", error=f"Checker error: {exc}"), 502


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