"""Environment validation and URL security checks."""

import os
import sys
import urllib.parse
from typing import List

from cli_logging.cli_logger import emit_structured_log
from cli_logging.logging_utils import Operation
from common import (
    ENV_AZURE_AI_OPENAI_ENDPOINT,
    ENV_AZURE_AI_API_VERSION,
    ENV_AZURE_AI_MODEL_NAME,
    ENV_AZURE_AI_PROJECT_ENDPOINT,
    ENV_WORK_IQ_A2A_ENDPOINT,
    ENV_WORK_IQ_A2A_CLIENT_ID,
    ENV_WORK_IQ_A2A_SCOPES,
    ENV_WORK_IQ_GRAPH_ENDPOINT,
    ENV_WORK_IQ_GRAPH_SCOPES,
    ENV_TENANT_ID,
    JUDGE_BACKEND_GITHUB_COPILOT,
)


# Allowed endpoints for URL validation: the WorkIQ A2A service (primary) and
# the Microsoft Graph gateway (fallback).
ALLOWED_ENDPOINTS = [
    'workiq.svc.cloud.microsoft',
    'graph.microsoft.com',
]


_AGENT_VARS = [
    ENV_WORK_IQ_A2A_ENDPOINT,
    ENV_WORK_IQ_A2A_CLIENT_ID,
    ENV_WORK_IQ_A2A_SCOPES,
    ENV_WORK_IQ_GRAPH_ENDPOINT,
    ENV_WORK_IQ_GRAPH_SCOPES,
    ENV_TENANT_ID,
]

_AZURE_VARS = [
    ENV_AZURE_AI_OPENAI_ENDPOINT,
    ENV_AZURE_AI_API_VERSION,
    ENV_AZURE_AI_MODEL_NAME,
]

_FOUNDRY_VARS = [
    ENV_AZURE_AI_PROJECT_ENDPOINT,
    ENV_AZURE_AI_MODEL_NAME,
]


def validate_environment(
    judge_backend: str = "azure",
    require_agent: bool = True,
) -> None:
    """Validate required environment variables.

    When ``require_agent`` is false, WorkIQ/A2A and tenant configuration is
    omitted so a captured response can be scored without agent access.

    - ``github-copilot`` judge backend: Azure vars aren't required (the Copilot
      SDK handles LLM access independently).
    - Foundry cloud evaluation (``AZURE_AI_PROJECT_ENDPOINT`` set): only the
      project endpoint + judge model deployment are required (Entra auth); the
      local Azure OpenAI ``AZURE_AI_OPENAI_ENDPOINT`` / ``AZURE_AI_API_KEY`` /
      ``AZURE_AI_API_VERSION`` vars are not needed.
    - Local Azure OpenAI evaluators (default): the local Azure vars are required.
    """
    if judge_backend == JUDGE_BACKEND_GITHUB_COPILOT:
        required_env_vars = []
    elif os.environ.get(ENV_AZURE_AI_PROJECT_ENDPOINT):
        required_env_vars = list(_FOUNDRY_VARS)
    else:
        required_env_vars = list(_AZURE_VARS)

    if require_agent:
        required_env_vars += _AGENT_VARS

    missing_vars = [
        var for var in required_env_vars if not os.environ.get(var)
    ]
    if missing_vars:
        emit_structured_log(
            "error",
            "Missing required environment variables: "
            f"{', '.join(missing_vars)}. Please ensure your .env file"
            " contains all required configuration.",
            operation=Operation.VALIDATE_ENV,
        )
        sys.exit(1)


def validate_endpoint_url(url: str, allowed_domains: List[str]) -> None:
    """Validate URL against security requirements."""
    try:
        parsed = urllib.parse.urlparse(url)
    except Exception as e:
        raise ValueError(f"Invalid URL format: {url}") from e

    if parsed.scheme in ['javascript', 'data']:
        raise ValueError(f"Dangerous URL scheme detected: {parsed.scheme}")

    if parsed.scheme != 'https':
        raise ValueError(f"Only HTTPS URLs are allowed, got: {parsed.scheme}")

    if parsed.netloc not in allowed_domains:
        raise ValueError(f"Domain not in allowed list: {parsed.netloc}")

    if parsed.fragment:
        raise ValueError("Fragment URLs are not allowed")
