import os
import subprocess


def load_shell_env(shell_script_path):
    # Run a shell that sources the script and prints the environment
    command = f"set -a && source {shell_script_path} && env"
    result = subprocess.run(["bash", "-c", command], capture_output=True, text=True, check=True)
    env = {}
    for line in result.stdout.splitlines():
        if "=" in line:
            key, value = line.split("=", 1)
            env[key] = value
    return env


env_vars = load_shell_env("constants/env_constants.sh")
URLS_DIR = env_vars["URLS_DIR"]
URLS_FILE_TEMPLATE = env_vars["URLS_FILE_TEMPLATE"]


# Paths for Agents and MLLM configs
LM_CONFIGS = "config/lm_configs.yaml"
AGENTS_CONFIG_DIR = "config/agent_config"

# Paths for outputs
DEFAULT_RESULTS_DIR = "./results"
RESULT_DIR_TEMPLATE = "{results_dir}/{model}/{domain}_{annotation}"
HTMLS_SUBDIR = "htmls"  # If '', saves HTML files directly to args.result_dir
TRAJECTORIES_SUBDIR = "trajectories"
LM_LOGS_DIR_TEMPLATE = f"{{result_dir}}/{TRAJECTORIES_SUBDIR}"
TRAJECTORY_DIR_TEMPLATE = f"{{result_dir}}/{TRAJECTORIES_SUBDIR}/{{task_id}}"
# If '', saves LM call logs directly to args.result_dir


# (V)WA specific
GOOGLE_FUZZY_MATCH_MODEL = "gemini-2.5-flash"
OPEN_AI_FUZZY_MATCH_MODEL = "gpt-5-2025-08-07"
HF_FUZZY_MATCH_MODEL = "meta-llama/Meta-Llama-3-8B-Instruct"
TEST_CONFIG_BASE_DIR = "config_files/vwa_not_vague/test_shopping"

RESET_ENV_SCRIPT = "scripts/environments/start_reset_envs.sh"
CLEAN_ENV_SCRIPT = "scripts/environments/clean_containers.sh"
AUTH_DIR = ".auth"

LOCAL_INPUT_IMAGES_DIR_TEMPLATE = "environment_docker/webarena-homepage/static/input_images/{domain}/task_{task_id}"

# Captioner
CAPTIONER_HOST_SCRIPT = "vwa_utils/host_captioner.py"
CAPTIONER_PORT = 9555
CAPTIONER_ENDPOINT = f"http://localhost:{CAPTIONER_PORT}/caption/"
CAPTIONER_SUPPORTED_MODELS = ["Salesforce/blip2-flan-t5-xl"]
CAPTIONER_DEFAULT_IMAGE_FORMAT = "PNG"

if __name__ == "__main__":
    print(f"URLS_DIR={URLS_DIR}")
    print(f"URLS_FILE_TEMPLATE={URLS_FILE_TEMPLATE}")
