"""
Configuration for contract HTTP tests.

Loads from .env file in this directory, with environment overrides.
"""

import os
import json
from pathlib import Path


def load_config() -> dict:
    """Load configuration from .env file and environment variables."""
    config = {}

    # Load from .env file in this directory
    env_file = Path(__file__).parent / ".env"
    if env_file.exists():
        with open(env_file) as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith("#") and "=" in line:
                    key, value = line.split("=", 1)
                    config[key.strip()] = value.strip()

    # Environment variables override .env file
    config["CONTRACT_TEST_URL"] = os.environ.get(
        "CONTRACT_TEST_URL",
        config.get("CONTRACT_TEST_URL", "")
    )
    config["CONTRACT_TEST_API_KEY"] = os.environ.get(
        "CONTRACT_TEST_API_KEY",
        config.get("CONTRACT_TEST_API_KEY", "")
    )

    return config


def load_environments() -> list:
    """Load available test environments from JSON file."""
    environments_file = Path(__file__).parent / "environments.json"

    if environments_file.exists():
        try:
            with open(environments_file) as f:
                return json.load(f)
        except Exception as e:
            print(f"Failed to load environments.json: {e}")

    # Default fallback
    config = load_config()
    return [
        {
            "id": "demo",
            "name": "Demo",
            "url": config.get("CONTRACT_TEST_URL", "https://demo.amarmascotas.ar"),
            "api_key": config.get("CONTRACT_TEST_API_KEY", ""),
            "description": "Demo environment",
            "default": True
        }
    ]


config = load_config()
environments = load_environments()
