"""
Management command to generate and send mock GitHub webhooks.

Usage:
    # Generate webhooks for all installations
    python manage.py generate_mock_webhooks

    # Dry run (don't actually send)
    python manage.py generate_mock_webhooks --dry-run

    # Generate specific count per installation
    python manage.py generate_mock_webhooks --count 10

    # Filter by event types
    python manage.py generate_mock_webhooks --event-types issues,pull_request

    # Target specific installation
    python manage.py generate_mock_webhooks --installation-id 12345678
"""

from __future__ import annotations

import json
from typing import Any

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

from mocking.services import MockWebhookService


class Command(BaseCommand):
    help = "Generate and send mock GitHub webhooks to the webhook endpoint"

    def add_arguments(self, parser):
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Show what would be sent without actually sending webhooks",
        )
        parser.add_argument(
            "--count",
            type=int,
            default=5,
            help="Number of webhooks to generate per installation (default: 5)",
        )
        parser.add_argument(
            "--event-types",
            type=str,
            help="Comma-separated list of event types (e.g., issues,pull_request,issue_comment)",
        )
        parser.add_argument(
            "--installation-id",
            type=int,
            help="Target a specific installation by ID",
        )
        parser.add_argument(
            "--json",
            action="store_true",
            help="Output results as JSON",
        )

    def handle(self, *args, **options):
        dry_run = options["dry_run"]
        count = options["count"]
        event_types_str = options.get("event_types")
        installation_id = options.get("installation_id")
        output_json = options.get("json")

        # Parse event types
        event_types = None
        if event_types_str:
            event_types = [t.strip() for t in event_types_str.split(",")]
            valid_types = {"issues", "pull_request", "issue_comment", "discussion", "pull_request_review"}
            invalid_types = set(event_types) - valid_types
            if invalid_types:
                raise CommandError(
                    f"Invalid event types: {', '.join(invalid_types)}. Valid types: {', '.join(valid_types)}"
                )

        service = MockWebhookService()

        if installation_id:
            # Target specific installation
            from integrations.models import GitHubInstallation

            try:
                installation = GitHubInstallation.objects.get(installation_id=installation_id)
            except GitHubInstallation.DoesNotExist as e:
                raise CommandError(f"Installation {installation_id} not found") from e

            results = service.generate_webhooks_for_installation(
                installation,
                count=count,
                event_types=event_types,
                dry_run=dry_run,
            )
            summary = {
                "total_installations": 1,
                "total_webhooks_sent": len(results),
                "installations": {
                    installation_id: {
                        "account": installation.account_login,
                        "webhooks_sent": len(results),
                        "results": results,
                    }
                },
            }
        else:
            # All installations
            summary = service.generate_webhooks_for_all_installations(
                count_per_installation=count,
                event_types=event_types,
                dry_run=dry_run,
            )

        # Output results
        if output_json:
            self.stdout.write(json.dumps(summary, indent=2))
        else:
            self._print_summary(summary, dry_run)

    def _print_summary(self, summary: dict[str, Any], dry_run: bool):
        """Print human-readable summary of webhook generation."""
        mode = "DRY RUN - " if dry_run else ""
        self.stdout.write(self.style.SUCCESS(f"\n{mode}Mock Webhook Generation Summary"))
        self.stdout.write("=" * 50)
        self.stdout.write(f"Total installations: {summary['total_installations']}")
        self.stdout.write(f"Total webhooks {'would be ' if dry_run else ''}sent: {summary['total_webhooks_sent']}")
        self.stdout.write("")

        for install_id, data in summary.get("installations", {}).items():
            self.stdout.write(self.style.HTTP_INFO(f"\nInstallation {install_id} ({data['account']})"))
            self.stdout.write(f"  Webhooks: {data['webhooks_sent']}")

            for result in data.get("results", []):
                status = result.get("status", "unknown")
                event = result.get("event_type", "unknown")
                repo = result.get("repository", "unknown")
                action = result.get("payload_preview", {}).get("action", "unknown")

                if status == "sent":
                    status_str = self.style.SUCCESS("✓ SENT")
                elif status == "dry_run":
                    status_str = self.style.WARNING("○ WOULD SEND")
                else:
                    status_str = self.style.ERROR(f"✗ {status}")

                self.stdout.write(f"  {status_str} {event}:{action} -> {repo}")

        self.stdout.write("")
