"""
Flush command for selective local reference data record removal.

All operations work on local cache only. Use 'czbg data upload' to sync changes to S3.
"""

import typer
from rich.console import Console
from rich.table import Table
from rich.prompt import Confirm
from typing import Optional

from ..common import BaseCommand
from src.services.versioning.local_cache_manager import LocalCacheManager
from src.services.versioning.models import FilterCriteria

console = Console()
app = typer.Typer(help="Flush (remove) local reference data records")


class FlushCommand(BaseCommand):
    """Flush command for selective local record removal."""

    def __init__(self):
        """Initialize with local cache manager."""
        super().__init__()
        self.cache_manager = LocalCacheManager()

    def flush_records(
        self,
        cloud_provider: str,
        service: Optional[str] = None,
        usage_family: Optional[str] = None,
        resource_type: Optional[str] = None,
        operation: Optional[str] = None,
        usage_type: Optional[str] = None,
        exact_match: bool = True,
        dry_run: bool = False,
        force: bool = False
    ):
        """
        Remove records matching filter criteria from local cache.

        Args:
            cloud_provider: Cloud provider to filter (required)
            service: Service name filter (optional)
            usage_family: Usage family filter (optional)
            resource_type: Resource type filter (optional)
            operation: Operation filter (optional)
            usage_type: Usage type filter (optional)
            exact_match: Use exact matching instead of substring matching
            dry_run: Preview what would be removed without actually removing
            force: Skip confirmation prompts
        """
        try:
            # Create filter criteria
            filters = FilterCriteria(
                cloud_provider=cloud_provider,
                service=service,
                usage_family=usage_family,
                resource_type=resource_type,
                operation=operation,
                usage_type=usage_type,
                exact_match=exact_match
            )

            # Show what will be removed
            console.print("🔍 Analyzing records to remove...", style="dim")
            preview = self.cache_manager.preview_flush(filters)

            if preview.records_to_remove == 0:
                console.print("ℹ️ No records match the specified criteria", style="yellow")
                return

            # Display preview
            self._display_flush_preview(preview, filters, dry_run)

            if dry_run:
                console.print("✅ Dry run completed - no changes made", style="green")
                return

            # Confirmation prompt
            if not force:
                if not self._confirm_flush_operation(preview):
                    console.print("❌ Operation cancelled by user", style="yellow")
                    return

            # Perform the flush
            console.print("🗑️  Removing records from local cache...", style="dim")
            result = self.cache_manager.flush_records(filters)

            # Display results
            self._display_flush_results(result)

            console.print("✅ Flush completed successfully!", style="green")

        except Exception as e:
            self.logger.error(f"Flush operation failed: {e}")
            console.print(f"❌ Error: {e}", style="red")

    def _display_flush_preview(self, preview, filters: FilterCriteria, is_dry_run: bool):
        """Display preview of what will be removed."""
        mode = "DRY RUN - " if is_dry_run else ""
        console.print(f"\n📋 {mode}Flush Preview", style="bold blue")
        console.print()

        # Filter summary
        filter_table = Table(show_header=False, box=None, padding=(0, 2))
        filter_table.add_column("Filter", style="cyan")
        filter_table.add_column("Value", style="white")

        filter_table.add_row("Cloud Provider", filters.cloud_provider)
        if filters.service:
            filter_table.add_row("Service", filters.service)
        if filters.usage_family:
            filter_table.add_row("Usage Family", filters.usage_family)
        if filters.resource_type:
            filter_table.add_row("Resource Type", filters.resource_type)
        if filters.operation:
            filter_table.add_row("Operation", filters.operation)
        if filters.usage_type:
            filter_table.add_row("Usage Type", filters.usage_type)

        filter_table.add_row("Match Mode", "Exact" if filters.exact_match else "Substring")

        console.print(filter_table)
        console.print()

        # Impact summary
        impact_table = Table(show_header=False, box=None, padding=(0, 2))
        impact_table.add_column("Metric", style="cyan")
        impact_table.add_column("Count", style="yellow", justify="right")

        impact_table.add_row("Records to remove", f"{preview.records_to_remove:,}")
        impact_table.add_row("Affected combinations", f"{preview.affected_combinations:,}")

        console.print(impact_table)

        # Sample records if available
        if preview.sample_records and len(preview.sample_records) > 0:
            console.print("\n📄 Sample Records (first 5):", style="bold cyan")
            sample_table = Table(show_header=True, header_style="bold blue")

            # Add columns based on first record
            first_record = preview.sample_records[0]
            for key in first_record.keys():
                if key in ["cloud_provider", "service", "usage_family", "resource_type"]:
                    sample_table.add_column(key.replace("_", " ").title())

            # Add sample rows
            for record in preview.sample_records[:5]:
                row = []
                for key in first_record.keys():
                    if key in ["cloud_provider", "service", "usage_family", "resource_type"]:
                        row.append(str(record.get(key, "")))
                sample_table.add_row(*row)

            console.print(sample_table)

        console.print()

    def _confirm_flush_operation(self, preview) -> bool:
        """Confirm flush operation with user."""
        if preview.records_to_remove > 1000:
            console.print("⚠️  WARNING: This will remove a large number of records!", style="bold red")
            console.print(f"   {preview.records_to_remove:,} records will be removed", style="red")
            console.print()

        console.print("🔄 This operation will:", style="bold yellow")
        console.print(f"  • Remove {preview.records_to_remove:,} records from local cache", style="dim")
        console.print(f"  • Affect {preview.affected_combinations:,} unique combinations", style="dim")
        console.print(f"  • Require 'czbg data upload' to sync changes to S3", style="dim")
        console.print()

        return Confirm.ask("Do you want to proceed with the flush operation?", default=False)

    def _display_flush_results(self, result):
        """Display the results of the flush operation."""
        console.print()
        console.print("📋 Flush Results", style="bold green")
        console.print()

        result_table = Table(show_header=False, box=None, padding=(0, 2))
        result_table.add_column("Metric", style="cyan")
        result_table.add_column("Value", style="white")

        result_table.add_row("Records Removed", f"{result.records_removed:,}")
        result_table.add_row("Local Changes", "✅ Yes" if result.local_changes_made else "❌ No")

        console.print(result_table)
        console.print()

        if result.local_changes_made:
            console.print("⚠️  " + result.sync_reminder, style="yellow")

        # Show updated cache info
        cache_info = self.cache_manager.get_cache_info()
        if cache_info:
            console.print(f"📊 Local cache now has {cache_info.record_count:,} combinations", style="dim")


# Create command instance
flush_cmd = FlushCommand()


@app.command()
def records(
    cloud_provider: str = typer.Option(..., "--cloud-provider", help="Cloud provider to filter (required)"),
    service: Optional[str] = typer.Option(None, "--service", help="Service name filter"),
    usage_family: Optional[str] = typer.Option(None, "--usage-family", help="Usage family filter"),
    resource_type: Optional[str] = typer.Option(None, "--resource-type", help="Resource type filter"),
    operation: Optional[str] = typer.Option(None, "--operation", help="Operation filter"),
    usage_type: Optional[str] = typer.Option(None, "--usage-type", help="Usage type filter"),
    exact_match: bool = typer.Option(True, "--exact/--substring", help="Use exact matching"),
    dry_run: bool = typer.Option(False, "--dry-run", help="Preview what would be removed"),
    force: bool = typer.Option(False, "--force", help="Skip confirmation prompts")
):
    """Remove records from local cache matching filter criteria."""
    flush_cmd.flush_records(
        cloud_provider=cloud_provider,
        service=service,
        usage_family=usage_family,
        resource_type=resource_type,
        operation=operation,
        usage_type=usage_type,
        exact_match=exact_match,
        dry_run=dry_run,
        force=force
    )