"""
Django management command to validate configuration settings.

This command validates all environment variables and configuration
settings, providing a detailed report of any issues found.

Usage:
    python manage.py validate_settings
    python manage.py validate_settings --strict
    python manage.py validate_settings --json
"""

import json
import sys

from django.core.management.base import BaseCommand

from config.settings.secrets import (
    check_secret_expiry,
    validate_required_secrets,
)
from config.settings.validation import (
    validate_all_settings,
)


class Command(BaseCommand):
    help = "Validate environment variables and configuration settings"

    def add_arguments(self, parser):
        parser.add_argument(
            "--strict",
            action="store_true",
            help="Treat warnings as errors",
        )
        parser.add_argument(
            "--json",
            action="store_true",
            help="Output results as JSON",
        )
        parser.add_argument(
            "--secrets-only",
            action="store_true",
            help="Only validate secrets",
        )

    def handle(self, *args, **options):
        strict = options["strict"]
        json_output = options["json"]
        secrets_only = options["secrets_only"]

        results = {
            "settings": None,
            "secrets": None,
            "expiry": None,
            "overall_valid": True,
        }

        # Validate secrets
        secret_errors = validate_required_secrets()
        expiry_warnings = check_secret_expiry()

        results["secrets"] = {
            "errors": secret_errors,
            "valid": len(secret_errors) == 0,
        }
        results["expiry"] = {
            "warnings": expiry_warnings,
        }

        if secret_errors:
            results["overall_valid"] = False

        # Validate general settings (unless secrets-only)
        if not secrets_only:
            settings_result = validate_all_settings(raise_on_error=False)
            results["settings"] = settings_result

            if not settings_result["valid"]:
                results["overall_valid"] = False

            if strict and settings_result["warnings"]:
                results["overall_valid"] = False

        # Output results
        if json_output:
            self.stdout.write(json.dumps(results, indent=2))
        else:
            self._print_human_readable(results, strict, secrets_only)

        # Exit with appropriate code
        if not results["overall_valid"]:
            sys.exit(1)

    def _print_human_readable(self, results, strict, secrets_only):
        """Print human-readable validation report."""
        self.stdout.write("")
        self.stdout.write("=" * 60)
        self.stdout.write(self.style.HTTP_INFO("ThrillWiki Configuration Validation"))
        self.stdout.write("=" * 60)
        self.stdout.write("")

        # Secret validation results
        self.stdout.write(self.style.HTTP_INFO("Secret Validation:"))
        self.stdout.write("-" * 40)

        if results["secrets"]["valid"]:
            self.stdout.write(self.style.SUCCESS("  ✓ All required secrets are valid"))
        else:
            self.stdout.write(self.style.ERROR("  ✗ Secret validation failed:"))
            for error in results["secrets"]["errors"]:
                self.stdout.write(self.style.ERROR(f"    - {error}"))

        # Secret expiry warnings
        if results["expiry"]["warnings"]:
            self.stdout.write("")
            self.stdout.write(self.style.WARNING("  Secret Expiry Warnings:"))
            for warning in results["expiry"]["warnings"]:
                self.stdout.write(self.style.WARNING(f"    - {warning}"))

        self.stdout.write("")

        # Settings validation results (if not secrets-only)
        if not secrets_only and results["settings"]:
            self.stdout.write(self.style.HTTP_INFO("Settings Validation:"))
            self.stdout.write("-" * 40)

            if results["settings"]["valid"]:
                self.stdout.write(self.style.SUCCESS("  ✓ All settings are valid"))
            else:
                self.stdout.write(self.style.ERROR("  ✗ Settings validation failed:"))
                for error in results["settings"]["errors"]:
                    self.stdout.write(self.style.ERROR(f"    - {error}"))

            # Warnings
            if results["settings"]["warnings"]:
                self.stdout.write("")
                self.stdout.write(self.style.WARNING("  Warnings:"))
                for warning in results["settings"]["warnings"]:
                    prefix = "✗" if strict else "!"
                    style = self.style.ERROR if strict else self.style.WARNING
                    self.stdout.write(style(f"    {prefix} {warning}"))

        self.stdout.write("")
        self.stdout.write("=" * 60)

        # Overall status
        if results["overall_valid"]:
            self.stdout.write(self.style.SUCCESS("Overall Status: PASSED"))
        else:
            self.stdout.write(self.style.ERROR("Overall Status: FAILED"))

        self.stdout.write("=" * 60)
        self.stdout.write("")
