"""
App Runner specific functionality and endpoints
"""

import os
import requests
from flask import Blueprint, jsonify, request
from yj.athenz.client import ZTSClient

# Create Blueprint for App Runner routes
bp = Blueprint("app_runner", __name__, url_prefix="/api/app_runner")
_athenz_key_path = "/var/run/athenz/service.key.pem"
_athenz_cert_path = "/var/run/athenz/service.cert.pem"


@bp.route("/env_vars", methods=["GET"])
@bp.route("/env_vars/<key>", methods=["GET"])
def get_env_vars(key=None):
    """
    Get environment variables from the App Runner environment.
    If key is provided, returns the value for that specific key.
    If no key is provided, returns all environment variables.
    """
    try:
        if key:
            # Return specific environment variable
            value = os.environ.get(key)
            if value is not None:
                return jsonify(
                    {"status": "success", "data": {"key": key, "value": value}}
                )
            return (
                jsonify(
                    {
                        "status": "error",
                        "message": f'Environment variable "{key}" not found',
                    }
                ),
                404,
            )
        # Return all environment variables
        env_vars = {}
        for k, v in os.environ.items():
            env_vars[k] = v

        return jsonify({"status": "success", "data": env_vars, "count": len(env_vars)})
    except Exception as e:
        return (
            jsonify(
                {
                    "status": "error",
                    "message": f"Failed to get App Runner environment information: {str(e)}",
                }
            ),
            500,
        )


@bp.route("/get_access_token", methods=["GET"])
def get_access_token():
    """
    Retrieve the IAM access token for the specified product domain.
    """
    product_domain = request.args.get("product_domain", "")
    if not product_domain:
        return jsonify({"success": False, "message": "No product domain provided"}), 400

    try:
        # Initialize ZTSClient with certificate and key paths
        client = ZTSClient.with_cert(_athenz_cert_path, _athenz_key_path)

        # Fetch the access token for the specified product domain
        res = client.get_access_token(domain=product_domain)

        return jsonify({"success": True, "access_token": res.access_token}), 200
    except Exception as e:
        return (
            jsonify(
                {
                    "success": False,
                    "message": f"Failed to retrieve access token: {str(e)}",
                }
            ),
            500,
        )


@bp.route("/send_request", methods=["GET"])
def send_request():
    """
    Send an HTTP GET request to the specified host and return the response.
    """
    host = request.args.get("host", "")
    if not host:
        return jsonify({"success": False, "message": "No host URL provided"}), 400

    try:
        response = requests.get(host, timeout=5)
        response.raise_for_status()
        return jsonify(
            {"success": True, "message": f"Connected to {host} successfully."}
        )
    except requests.RequestException as e:
        return jsonify({"success": False, "message": str(e)}), 500


@bp.route("/validate_volume", methods=["POST"])
def validate_volume():
    """
    Validate if a file exists in the specified path for a given key.
    If the file exists, read and return its contents.
    """
    try:
        data = request.json
        key = data.get("key")
        path = data.get("path")

        if not key or not path:
            return (
                jsonify({"success": False, "message": "Missing required parameters"}),
                400,
            )

        # Construct the full file path
        file_path = os.path.join(path, key)

        # Check if the file exists
        if os.path.exists(file_path):
            try:
                with open(file_path, "r", encoding="utf-8") as file:
                    content = file.read()
                return (
                    jsonify(
                        {
                            "success": True,
                            "message": f"File exists at path '{file_path}'.",
                            "content": content,
                        }
                    ),
                    200,
                )
            except Exception as e:
                return (
                    jsonify(
                        {
                            "success": False,
                            "message": f"File exists but could not be read: {str(e)}",
                        }
                    ),
                    500,
                )
        return (
            jsonify(
                {
                    "success": False,
                    "message": f"File does not exist at path '{file_path}'.",
                }
            ),
            404,
        )
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 500
