from typing import Optional
"""
Enhanced import commands for reference datasets with conflict resolution.
"""

from pathlib import Path

import typer
from rich.console import Console

from ..common import BaseCommand, display_summary_table
from .import_session import ImportSessionManager
from .import_tools import ImportAnalyzer, InteractiveImporter

console = Console()
app = typer.Typer(help="Import data to reference datasets")


class ImportCommand(BaseCommand):
    """Import command with conflict resolution."""

    def __init__(self):
        super().__init__()
        self.session_manager = ImportSessionManager()

    def import_to_reference(
        self,
        source_file: str,
        interactive: bool = False,
        session_id: Optional[str] = None,
        preview_only: bool = False,
        reference_file: str = "data/providers.csv",
    ):
        """Import data to reference dataset."""
        try:
            source_path = Path(source_file)
            reference_path = Path(reference_file)

            self.validate_file_exists(source_path, "source CSV file")

            if preview_only:
                self._preview_import(source_path, reference_path, "reference")
                return

            if interactive:
                importer = InteractiveImporter(self.session_manager)
                result = importer.run_interactive_import(
                    source_path, "reference", reference_path, session_id
                )
                self._display_import_result(result)
            else:
                self._run_automatic_import(source_path, reference_path, "reference")

        except Exception as e:
            self.handle_exception(e, "reference import")

    def import_to_usage_reference(
        self,
        source_file: str,
        interactive: bool = False,
        session_id: Optional[str] = None,
        preview_only: bool = False,
        usage_reference_file: str = "data/usage_reference/usage_standards.parquet",
    ):
        """Import data to usage-reference dataset."""
        try:
            source_path = Path(source_file)
            usage_ref_path = Path(usage_reference_file)

            self.validate_file_exists(source_path, "source CSV file")

            if preview_only:
                self._preview_import(source_path, usage_ref_path, "usage-reference")
                return

            if interactive:
                importer = InteractiveImporter(self.session_manager)
                result = importer.run_interactive_import(
                    source_path, "usage-reference", usage_ref_path, session_id
                )
                self._display_import_result(result)
            else:
                self._run_automatic_import(
                    source_path, usage_ref_path, "usage-reference"
                )

        except Exception as e:
            self.handle_exception(e, "usage-reference import")

    def list_sessions(self):
        """List all import sessions."""
        try:
            sessions = self.session_manager.list_sessions()

            if not sessions:
                self.console.print("[yellow]No import sessions found[/yellow]")
                return

            display_summary_table(
                self.console,
                "Import Sessions",
                sessions,
                [
                    "session_id",
                    "target_dataset",
                    "source_file",
                    "progress",
                    "completed",
                ],
            )

        except Exception as e:
            self.handle_exception(e, "session listing")

    def cleanup_sessions(self, keep_days: int = 7):
        """Clean up old completed sessions."""
        try:
            self.session_manager.cleanup_completed_sessions(keep_days)
            self.display_success(
                f"Cleaned up completed sessions older than {keep_days} days"
            )

        except Exception as e:
            self.handle_exception(e, "session cleanup")

    def delete_session(self, session_id: str):
        """Delete a specific session."""
        try:
            self.session_manager.delete_session(session_id)
            self.display_success(f"Deleted session: {session_id}")

        except Exception as e:
            self.handle_exception(e, "session deletion")

    def _preview_import(
        self, source_path: Path, target_path: Path, target_dataset: str
    ):
        """Preview import without making changes."""
        import polars as pl

        self.console.print(
            f"[blue]Analyzing import to {target_dataset} dataset...[/blue]"
        )

        # Load data
        new_df = pl.read_csv(source_path)

        if target_dataset == "reference":
            existing_df = (
                pl.read_csv(target_path) if target_path.exists() else pl.DataFrame()
            )
        else:
            existing_df = (
                pl.read_parquet(target_path) if target_path.exists() else pl.DataFrame()
            )

        # Analyze
        analyzer = ImportAnalyzer(target_dataset)
        analysis = analyzer.analyze_import(existing_df, new_df)

        # Display results
        summary_data = [
            {"metric": "Total new records", "value": analysis["total_new_records"]},
            {"metric": "Exact duplicates", "value": analysis["exact_duplicates"]},
            {
                "metric": "Conflicts requiring resolution",
                "value": analysis["conflicts"],
            },
            {"metric": "Net new records", "value": analysis["net_new_records"]},
        ]

        display_summary_table(
            self.console,
            f"Import Analysis - {target_dataset}",
            summary_data,
            ["metric", "value"],
        )

        # Show conflict details if any
        if analysis["conflicts"] > 0:
            self.console.print(
                f"\n[yellow]Conflicts found ({analysis['conflicts']}):[/yellow]"
            )
            for i, conflict in enumerate(
                analysis["conflicts_list"][:5]
            ):  # Show first 5
                self.console.print(f"  {i + 1}. {conflict.get_summary()}")

            if analysis["conflicts"] > 5:
                self.console.print(f"  ... and {analysis['conflicts'] - 5} more")

            self.console.print("\n[blue]Use --interactive to resolve conflicts[/blue]")

    def _run_automatic_import(
        self, source_path: Path, target_path: Path, target_dataset: str
    ):
        """Run automatic import (net new records only)."""
        import polars as pl

        self.console.print(
            f"[blue]Running automatic import to {target_dataset}...[/blue]"
        )

        # Load data
        new_df = pl.read_csv(source_path)

        if target_dataset == "reference":
            existing_df = (
                pl.read_csv(target_path) if target_path.exists() else pl.DataFrame()
            )
        else:
            existing_df = (
                pl.read_parquet(target_path) if target_path.exists() else pl.DataFrame()
            )

        # Analyze
        analyzer = ImportAnalyzer(target_dataset)
        analysis = analyzer.analyze_import(existing_df, new_df)

        if analysis["conflicts"] > 0:
            self.console.print(
                f"[red]Cannot proceed: {analysis['conflicts']} conflicts found[/red]"
            )
            self.console.print(
                "[blue]Use --interactive to resolve conflicts or --preview to analyze[/blue]"
            )
            return

        # Add net new records
        if analysis["net_new_records"] > 0:
            net_new_df = pl.DataFrame(analysis["net_new_list"])
            result_df = pl.concat([existing_df, net_new_df], how="vertical")

            # Save result
            if target_dataset == "reference":
                result_df.write_csv(target_path)
            else:
                result_df.write_parquet(target_path)

            self.display_success(
                f"Import completed for {target_dataset}",
                {
                    "Records added": analysis["net_new_records"],
                    "Duplicates skipped": analysis["exact_duplicates"],
                },
            )
        else:
            self.console.print("[yellow]No new records to import[/yellow]")

    def _display_import_result(self, result: dict):
        """Display import result."""
        if result["status"] == "completed":
            self.display_success(
                "Import completed successfully",
                {
                    "Conflicts resolved": result.get("conflicts_resolved", 0),
                    "Records added": result.get("records_added", 0),
                },
            )
        elif result["status"] == "paused":
            self.console.print("[yellow]Import paused. Resume with:[/yellow]")
            self.console.print(f"[green]--session={result['session_id']}[/green]")
        else:
            self.console.print(
                f"[red]Import failed: {result.get('message', 'Unknown error')}[/red]"
            )


# Create command instance
import_cmd = ImportCommand()


@app.command()
def reference(
    source_file: str = typer.Argument(..., help="Path to source CSV file"),
    interactive: bool = typer.Option(
        False, "--interactive", "-i", help="Enable interactive conflict resolution"
    ),
    session_id: Optional[str] = typer.Option(
        None, "--session", help="Resume from existing session"
    ),
    preview_only: bool = typer.Option(
        False, "--preview", help="Preview import without making changes"
    ),
    reference_file: str = typer.Option(
        "data/providers.csv", "--target", help="Target reference file"
    ),
):
    """Import data to reference dataset."""
    import_cmd.import_to_reference(
        source_file, interactive, session_id, preview_only, reference_file
    )


@app.command()
def usage_reference(
    source_file: str = typer.Argument(..., help="Path to source CSV file"),
    interactive: bool = typer.Option(
        False, "--interactive", "-i", help="Enable interactive conflict resolution"
    ),
    session_id: Optional[str] = typer.Option(
        None, "--session", help="Resume from existing session"
    ),
    preview_only: bool = typer.Option(
        False, "--preview", help="Preview import without making changes"
    ),
    usage_reference_file: str = typer.Option(
        "data/usage_reference/usage_standards.parquet",
        "--target",
        help="Target usage-reference file",
    ),
):
    """Import data to usage-reference dataset."""
    import_cmd.import_to_usage_reference(
        source_file, interactive, session_id, preview_only, usage_reference_file
    )


@app.command()
def sessions():
    """List all import sessions."""
    import_cmd.list_sessions()


@app.command()
def cleanup(
    keep_days: int = typer.Option(
        7, "--days", help="Keep completed sessions for this many days"
    ),
):
    """Clean up old completed sessions."""
    import_cmd.cleanup_sessions(keep_days)


@app.command()
def delete_session(session_id: str = typer.Argument(..., help="Session ID to delete")):
    """Delete a specific session."""
    import_cmd.delete_session(session_id)
