from typing import Optional
"""
Usage-reference import commands with consistent interface.
"""

from pathlib import Path

import typer

from ..common import BaseCommand
from ..reference.import_session import ImportSessionManager
from ..reference.import_tools import InteractiveImporter

app = typer.Typer(help="Import data to usage-reference dataset")


class UsageReferenceImportCommand(BaseCommand):
    """Usage-reference import with same interface as reference import."""

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

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

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

            if preview_only:
                self._preview_import(source_path, target_path)
                return

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

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

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

        from ..reference.import_tools import ImportAnalyzer

        self.console.print(
            "[blue]Analyzing import to usage-reference dataset...[/blue]"
        )

        # Load data
        new_df = pl.read_csv(source_path)
        existing_df = (
            pl.read_parquet(target_path) if target_path.exists() else pl.DataFrame()
        )

        # Analyze
        analyzer = ImportAnalyzer("usage-reference")
        analysis = analyzer.analyze_import(existing_df, new_df)

        # Display results (same as reference import)
        from ..common import display_summary_table

        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,
            "Import Analysis - Usage-Reference",
            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):
        """Run automatic import (net new records only)."""
        import polars as pl

        from ..reference.import_tools import ImportAnalyzer

        self.console.print(
            "[blue]Running automatic import to usage-reference...[/blue]"
        )

        # Load data
        new_df = pl.read_csv(source_path)
        existing_df = (
            pl.read_parquet(target_path) if target_path.exists() else pl.DataFrame()
        )

        # Analyze
        analyzer = ImportAnalyzer("usage-reference")
        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
            result_df.write_parquet(target_path)

            self.display_success(
                "Import completed for usage-reference",
                {
                    "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(
                "Usage-reference 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 = UsageReferenceImportCommand()


@app.command()
def data(
    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"
    ),
    target_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, target_file
    )
