"""
Management command to generate E2E tests from user_flows.yaml.

Usage:
    # Generate all E2E tests
    python manage.py generate_e2e_tests

    # Generate for specific flow
    python manage.py generate_e2e_tests --flow auth_signup

    # Specify output directory
    python manage.py generate_e2e_tests --output tests/e2e/

    # Dry run (show what would be generated)
    python manage.py generate_e2e_tests --dry-run
"""

import logging
from pathlib import Path

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

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = "Generate E2E tests from user_flows.yaml SST definitions"

    def add_arguments(self, parser):
        parser.add_argument(
            "--flow",
            type=str,
            help="Generate tests for specific flow only",
        )
        parser.add_argument(
            "--output",
            "-o",
            type=str,
            help="Output directory for generated tests (default: tests/e2e/generated/)",
        )
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Show what would be generated without writing files",
        )
        parser.add_argument(
            "--list",
            action="store_true",
            help="List all available flows",
        )

    def handle(self, *args, **options):
        flow_name = options.get("flow")
        output_dir = options.get("output")
        dry_run = options.get("dry_run", False)
        list_flows = options.get("list", False)

        # Import here to avoid circular imports
        from lightwave.schema.core.registry import build_registry

        # Build registry from YAML
        registry = build_registry(use_db=False)

        if list_flows:
            self._list_flows(registry)
            return

        # Determine output directory
        if output_dir:
            out_path = Path(output_dir)
        else:
            out_path = Path(settings.BASE_DIR) / "tests" / "e2e" / "generated"

        if flow_name:
            # Generate single flow
            self._generate_single_flow(flow_name, out_path, dry_run, registry)
        else:
            # Generate all flows
            self._generate_all_flows(out_path, dry_run)

    def _list_flows(self, registry):
        """List all available flows."""
        self.stdout.write("\nAvailable user flows:\n")
        self.stdout.write("=" * 60)

        for flow in registry.user_flows.all():
            self.stdout.write(f"\n  {flow.name}")
            self.stdout.write(f"    Display: {flow.display_name}")
            if flow.requires_user_type:
                self.stdout.write(f"    Requires: {flow.requires_user_type}")
            self.stdout.write(f"    Steps: {len(flow.steps)}")
            if flow.entry_points:
                self.stdout.write(f"    Entry points: {len(flow.entry_points)}")

        self.stdout.write(f"\n\nTotal: {len(registry.user_flows.names())} flows\n")

    def _generate_single_flow(self, flow_name, out_path, dry_run, registry):
        """Generate tests for a single flow."""
        from lightwave.schema.testing.generators import generate_flow_test_class

        flow = registry.user_flows.get(flow_name)
        if not flow:
            raise CommandError(f"Flow '{flow_name}' not found in user_flows.yaml")

        self.stdout.write(f"\nGenerating tests for flow: {flow_name}")
        self.stdout.write(f"  Display name: {flow.display_name}")
        self.stdout.write(f"  Steps: {len(flow.steps)}")

        code = generate_flow_test_class(flow_name)
        filename = f"test_{flow_name}.py"
        filepath = out_path / filename

        if dry_run:
            self.stdout.write(f"\nWould write to: {filepath}")
            self.stdout.write("\n" + "=" * 60 + "\n")
            self.stdout.write(code)
            self.stdout.write("\n" + "=" * 60)
        else:
            out_path.mkdir(parents=True, exist_ok=True)
            filepath.write_text(code)
            self.stdout.write(self.style.SUCCESS(f"\n✓ Generated: {filepath}"))

    def _generate_all_flows(self, out_path, dry_run):
        """Generate tests for all flows."""
        from lightwave.schema.testing.generators import generate_all_flow_tests

        self.stdout.write("\nGenerating E2E tests from user_flows.yaml...")

        if dry_run:
            generated = generate_all_flow_tests(output_dir=None)
            self.stdout.write(f"\nWould generate {len(generated)} test files:")
            for filename in sorted(generated.keys()):
                self.stdout.write(f"  - {out_path / filename}")
            self.stdout.write(f"\nOutput directory: {out_path}")
        else:
            generated = generate_all_flow_tests(output_dir=str(out_path))
            self.stdout.write(self.style.SUCCESS(f"\n✓ Generated {len(generated)} test files"))
            self.stdout.write(f"  Output: {out_path}")

            # List generated files
            self.stdout.write("\nGenerated files:")
            for filename in sorted(generated.keys()):
                self.stdout.write(f"  - {filename}")

            # Instructions
            self.stdout.write("\n" + "=" * 60)
            self.stdout.write("\nTo run the generated tests:")
            self.stdout.write(f"  pytest {out_path} -v")
            self.stdout.write("\nNote: These tests pull all values from the SST.")
            self.stdout.write("      Update user_flows.yaml to change test behavior.")
