from django.core.management.base import BaseCommand, CommandError

from config.proxy import build_proxy_url_from_proxychains_env, resolve_requests_proxy_url
from location_data.openeo_service import (
    OpenEOAuthenticationError,
    OpenEOConnectionSettings,
    OpenEOServiceError,
    connect_openeo,
    is_openeo_auth_configured,
)


class Command(BaseCommand):
    help = "Verify openEO connectivity and authentication using the current environment."

    def add_arguments(self, parser):
        parser.add_argument(
            "--skip-if-unconfigured",
            action="store_true",
            help="Exit successfully when the required auth environment variables are missing.",
        )

    def handle(self, *args, **options):
        settings = OpenEOConnectionSettings.from_env()
        if not is_openeo_auth_configured(settings):
            message = "openEO auth check skipped because the required credentials are not configured."
            if options["skip_if_unconfigured"]:
                self.stdout.write(self.style.WARNING(message))
                return
            raise CommandError(message)

        self.stdout.write(f"Verifying openEO auth against {settings.backend_url}...")
        requests_proxy_url = resolve_requests_proxy_url(settings.proxy_url)
        proxychains_url = build_proxy_url_from_proxychains_env()
        if requests_proxy_url:
            self.stdout.write(f"Using requests proxy for openEO auth: {requests_proxy_url}")
        elif proxychains_url:
            self.stdout.write(f"Using proxychains for openEO auth: {proxychains_url}")

        try:
            connect_openeo(settings)
        except OpenEOAuthenticationError as exc:
            raise CommandError(str(exc)) from exc
        except OpenEOServiceError as exc:
            raise CommandError(str(exc)) from exc

        self.stdout.write(self.style.SUCCESS("openEO authentication succeeded."))
