from __future__ import annotations

import shlex
from typing import Mapping


_SCRIPT_VARIABLES = {
    "VPN_USER_PREFIX": "WAWA_VPN_USER_PREFIX",
    "VPN_PASSWORD": "WAWA_PASSWORD",
    "VPN_IPSEC_PSK": "WAWA_PASSWORD",
    "SOCKS_USER": "WAWA_SOCKS_USER",
    "SOCKS_PASSWORD": "WAWA_PASSWORD",
    "SOCKS_PASS": "WAWA_PASSWORD",
    "SOCKS_PORT": "WAWA_SOCKS_PORT",
    "XRAY_USER": "WAWA_SOCKS_USER",
    "XRAY_PASS": "WAWA_PASSWORD",
    "XRAY_PORT": "WAWA_SOCKS_PORT",
    "PSK_KEY": "WAWA_PASSWORD",
    "VPN_PASS": "WAWA_PASSWORD",
    "L2TP_PSK": "WAWA_PASSWORD",
    "L2TP_PASS": "WAWA_PASSWORD",
    "VPN_IPSEC_PSK_DEFAULT": "WAWA_PASSWORD",
    "VPN_PASSWORD_DEFAULT": "WAWA_PASSWORD",
    "SOCKS_USER_DEFAULT": "WAWA_SOCKS_USER",
    "SOCKS_PASSWORD_DEFAULT": "WAWA_PASSWORD",
    "SOCKS_PASS_DEFAULT": "WAWA_PASSWORD",
    "SOCKS_PORT_DEFAULT": "WAWA_SOCKS_PORT",
}


def shell_env_assignments(values: Mapping[str, str]) -> str:
    return " ".join(f"{key}={shlex.quote(str(value))}" for key, value in values.items())


def configured_default_script_command(script_url: str, env: Mapping[str, str]) -> str:
    """Download a default script, patch known defaults, and run it with custom connection settings."""
    helper_env = {
        "WAWA_VPN_USER_PREFIX": str(env.get("VPN_USER_PREFIX") or "user"),
        "WAWA_SOCKS_USER": str(env.get("SOCKS_USER") or env.get("XRAY_USER") or "root"),
        "WAWA_PASSWORD": str(
            env.get("SOCKS_PASSWORD")
            or env.get("SOCKS_PASS")
            or env.get("VPN_PASSWORD")
            or env.get("VPN_PASS")
            or env.get("L2TP_PASS")
            or "wawacloud"
        ),
        "WAWA_SOCKS_PORT": str(env.get("SOCKS_PORT") or env.get("XRAY_PORT") or "23456"),
    }
    exports = shell_env_assignments(helper_env)
    variable_cases = "\n".join(
        f"/^[[:space:]]*{name}=/ {{print \"{name}=\" q(ENVIRON[\"{env_name}\"]); next}}"
        for name, env_name in _SCRIPT_VARIABLES.items()
    )
    awk_script = (
        "function q(v){gsub(/\\\\/,\"\\\\\\\\\",v); gsub(/\\\"/,\"\\\\\\\"\",v); return \"\\\"\" v \"\\\"\"}\n"
        f"{variable_cases}\n"
        "{print}"
    )
    return f"{exports}; export WAWA_VPN_USER_PREFIX WAWA_SOCKS_USER WAWA_PASSWORD WAWA_SOCKS_PORT; bash <(curl -fsSL {shlex.quote(script_url)} | awk {shlex.quote(awk_script)})"
