#!/usr/bin/env python3

from flask import Flask, render_template, request, Response, abort
import requests
import os
from urllib.parse import urlparse

app = Flask(__name__)


@app.route("/", methods=["GET", "POST"])
def home():
    """
    Render the home page with the input URL.
    """
    url = request.form.get("url", "")
    return render_template("index.html", url=url)


@app.route("/fetch", methods=["GET"])
def fetch():
    """
    Fetch the content from the provided URL and return the response.
    """
    url = request.args.get("url")
    if not url:
        return "No URL provided", 400

    if urlparse(url).hostname in ["localhost", "127.0.0.1"]:
        return "Forbidden", 403

    try:
        response = requests.get(url)
        return Response(
            response.content,
            status=response.status_code,
            content_type=response.headers.get("Content-Type"),
        )
    except requests.exceptions.RequestException as e:
        return f"Error fetching the URL: {e}", 500


@app.route("/flag", methods=["GET"])
def flag():
    """
    PS: You've to access this resource from localhost to get the flag.
    """
    if request.remote_addr != "127.0.0.1":
        abort(403, description="You are not allowed to access this resource")
 
    try:
        with open("/flag.txt") as flag_file:
            return flag_file.read()
    except Exception as e:
        return f"Error reading the flag file: {e}", 500


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