"""
OSINT CLI Commands - Dark web reconnaissance command group

Provides CLI interface for OSINT investigations including:
- Quick scans
- Deep investigations
- Status checking
- History viewing
"""

import sys
from pathlib import Path
from typing import Optional

import click
from rich.console import Console
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.table import Table

console = Console()


@click.group()
def osint():
    """OSINT reconnaissance commands for dark web intelligence gathering.

    These commands require Tor daemon running on localhost:9050.
    """
    pass


@osint.command("scan")
@click.argument("query")
@click.option(
    "--model",
    "-m",
    default="claude-sonnet-4-20250514",
    help="LLM model for analysis",
    show_default=True,
)
@click.option(
    "--threads",
    "-t",
    default=5,
    type=int,
    help="Number of concurrent threads",
    show_default=True,
)
@click.option(
    "--output",
    "-o",
    type=click.Path(),
    help="Output file path for report",
)
@click.option(
    "--no-report",
    is_flag=True,
    help="Skip report generation",
)
def osint_scan(query: str, model: str, threads: int, output: Optional[str], no_report: bool):
    """Quick OSINT scan for a query.

    Performs a fast scan across dark web search engines with basic
    artifact extraction. Use 'osint deep' for comprehensive analysis.

    Example:
        groknroll osint scan "ransomware lockbit"
    """
    from groknroll.agents.osint_agent import OsintAgent

    project_path = Path.cwd()
    output_path = Path(output) if output else None

    try:
        with Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            console=console,
        ) as progress:
            task = progress.add_task("Initializing OSINT agent...", total=None)

            # Initialize agent
            agent = OsintAgent(
                project_path=project_path,
                model=model,
                max_workers=threads,
                output_dir=output_path.parent if output_path else None,
            )

            # Check Tor status
            progress.update(task, description="Checking Tor connectivity...")
            status = agent.check_status()
            if not status["tor_connected"]:
                console.print(
                    "[bold red]Error:[/bold red] Tor proxy not available at "
                    f"{status['tor_proxy']}. Ensure Tor daemon is running."
                )
                sys.exit(1)

            console.print(f"[dim]Tor connected via {status['tor_ip']}[/dim]")

            # Run investigation
            progress.update(task, description=f"Searching dark web for '{query}'...")
            result = agent.investigate(
                query=query,
                deep=False,
                save_report=not no_report,
            )

        # Display results
        console.print()
        _display_investigation_result(result)

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@osint.command("deep")
@click.argument("query")
@click.option(
    "--model",
    "-m",
    default="claude-sonnet-4-20250514",
    help="LLM model for analysis",
    show_default=True,
)
@click.option(
    "--threads",
    "-t",
    default=10,
    type=int,
    help="Number of concurrent threads",
    show_default=True,
)
@click.option(
    "--output",
    "-o",
    type=click.Path(),
    help="Output file path for report",
)
@click.option(
    "--engines",
    "-e",
    multiple=True,
    help="Specific search engines to use (can be repeated)",
)
def osint_deep(
    query: str,
    model: str,
    threads: int,
    output: Optional[str],
    engines: tuple[str, ...],
):
    """Deep OSINT investigation with LLM analysis.

    Performs comprehensive investigation including:
    - Query refinement with LLM
    - Search across all dark web engines
    - Result filtering with LLM
    - Content scraping
    - Artifact extraction
    - LLM-powered analysis
    - Detailed report generation

    Example:
        groknroll osint deep "threat actor APT29" --threads 10
    """
    from groknroll.agents.osint_agent import OsintAgent

    project_path = Path.cwd()
    output_path = Path(output) if output else None

    try:
        with Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            console=console,
        ) as progress:
            task = progress.add_task("Initializing OSINT agent...", total=None)

            # Initialize agent
            agent = OsintAgent(
                project_path=project_path,
                model=model,
                max_workers=threads,
                output_dir=output_path.parent if output_path else None,
            )

            # Check Tor status
            progress.update(task, description="Checking Tor connectivity...")
            status = agent.check_status()
            if not status["tor_connected"]:
                console.print(
                    "[bold red]Error:[/bold red] Tor proxy not available at "
                    f"{status['tor_proxy']}. Ensure Tor daemon is running."
                )
                sys.exit(1)

            console.print(f"[dim]Tor connected via {status['tor_ip']}[/dim]")

            # Run deep investigation
            progress.update(task, description=f"Running deep investigation for '{query}'...")
            result = agent.investigate(
                query=query,
                deep=True,
                save_report=True,
                engines=list(engines) if engines else None,
            )

        # Display results
        console.print()
        _display_investigation_result(result, detailed=True)

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@osint.command("status")
def osint_status():
    """Check Tor connectivity and engine availability.

    Verifies that:
    - Tor daemon is running and accessible
    - Tor proxy is functioning (shows exit IP)
    - All search engines are configured

    Example:
        groknroll osint status
    """
    from groknroll.agents.osint_agent import OsintAgent

    project_path = Path.cwd()

    try:
        agent = OsintAgent(project_path=project_path)
        status = agent.check_status()

        console.print()
        console.print(
            Panel.fit(
                _format_status(status),
                title="[bold cyan]OSINT Status[/bold cyan]",
                border_style="cyan",
            )
        )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@osint.command("engines")
def osint_engines():
    """List available dark web search engines.

    Shows all configured search engines with their .onion addresses.

    Example:
        groknroll osint engines
    """
    from groknroll.osint.dark_web_search import SEARCH_ENGINES

    table = Table(title="Dark Web Search Engines")
    table.add_column("Name", style="cyan")
    table.add_column("URL Template", style="dim")

    for name, url in sorted(SEARCH_ENGINES.items()):
        # Truncate long URLs
        display_url = url[:60] + "..." if len(url) > 60 else url
        table.add_row(name, display_url)

    console.print()
    console.print(table)
    console.print(f"\n[dim]Total: {len(SEARCH_ENGINES)} engines[/dim]")


@osint.command("extract")
@click.argument("file_path", type=click.Path(exists=True))
@click.option(
    "--type",
    "-t",
    "artifact_type",
    type=click.Choice(
        ["email", "btc_legacy", "btc_bech32", "eth", "onion", "ip_v4", "phone", "username", "xmr"]
    ),
    help="Extract specific artifact type only",
)
def osint_extract(file_path: str, artifact_type: Optional[str]):
    """Extract intelligence artifacts from a file.

    Scans file content for indicators like:
    - Email addresses
    - Bitcoin/Ethereum/Monero addresses
    - .onion domains
    - IP addresses
    - Phone numbers
    - Usernames

    Example:
        groknroll osint extract scraped_content.txt
        groknroll osint extract data.txt --type email
    """
    from groknroll.osint.artifact_extractor import ArtifactExtractor

    try:
        # Read file
        with open(file_path, encoding="utf-8") as f:
            content = f.read()

        extractor = ArtifactExtractor()

        if artifact_type:
            artifacts = extractor.extract_by_type(content, artifact_type, file_path)
        else:
            artifacts = extractor.extract_all(content, file_path)

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

        # Display results
        table = Table(title=f"Extracted Artifacts from {Path(file_path).name}")
        table.add_column("Type", style="cyan")
        table.add_column("Value", style="green")
        table.add_column("Confidence", justify="right")

        for artifact in artifacts[:100]:  # Limit display
            table.add_row(
                artifact.artifact_type,
                artifact.value[:60],
                f"{artifact.confidence:.0%}",
            )

        console.print()
        console.print(table)

        if len(artifacts) > 100:
            console.print(f"\n[dim]Showing 100 of {len(artifacts)} artifacts[/dim]")

        # Show summary
        summary = extractor.extract_summary(content, file_path)
        console.print("\n[bold]Summary:[/bold]")
        for art_type, count in sorted(summary.items()):
            console.print(f"  {art_type}: {count}")

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


def _display_investigation_result(result, detailed: bool = False):
    """Display investigation result to console."""
    # Status panel
    status_color = "green" if result.status == "complete" else "red"
    status_text = f"[bold {status_color}]{result.status.upper()}[/bold {status_color}]"

    if result.error:
        status_text += f"\n[yellow]{result.error}[/yellow]"

    console.print(
        Panel.fit(
            f"[bold]Query:[/bold] {result.query}\n"
            f"[bold]Refined:[/bold] {result.refined_query}\n"
            f"[bold]Status:[/bold] {status_text}\n"
            f"[bold]Duration:[/bold] {result.duration:.1f}s",
            title="[bold cyan]OSINT Investigation[/bold cyan]",
            border_style="cyan",
        )
    )

    # Statistics table
    table = Table(show_header=True)
    table.add_column("Metric", style="cyan")
    table.add_column("Value", justify="right", style="green")

    table.add_row("Search Results", str(result.results_count))
    table.add_row("Pages Scraped", str(result.scraped_count))
    table.add_row("Artifacts Found", str(result.artifacts_count))

    console.print()
    console.print(table)

    # Artifacts summary
    if result.artifacts:
        artifact_types: dict[str, int] = {}
        for artifact in result.artifacts:
            artifact_types[artifact.artifact_type] = (
                artifact_types.get(artifact.artifact_type, 0) + 1
            )

        console.print("\n[bold]Artifacts by Type:[/bold]")
        for art_type, count in sorted(artifact_types.items()):
            console.print(f"  - {art_type}: {count}")

    # Key findings (if deep mode)
    if detailed and result.report and result.report.key_findings:
        console.print("\n[bold]Key Findings:[/bold]")
        for finding in result.report.key_findings:
            console.print(f"  • {finding}")

    # Report path
    if result.report_path:
        console.print(f"\n[bold]Report saved to:[/bold] {result.report_path}")


def _format_status(status: dict) -> str:
    """Format status dictionary for display."""
    lines = []

    # Tor status
    if status["tor_connected"]:
        lines.append("[bold green]✓ Tor Connected[/bold green]")
        lines.append(f"  Proxy: {status['tor_proxy']}")
        if status.get("tor_ip"):
            lines.append(f"  Exit IP: {status['tor_ip']}")
    else:
        lines.append("[bold red]✗ Tor Not Connected[/bold red]")
        lines.append(f"  Proxy: {status['tor_proxy']}")
        lines.append("  [yellow]Ensure Tor daemon is running[/yellow]")

    lines.append("")

    # Engines
    lines.append(f"[bold]Search Engines:[/bold] {status['engines_available']}")

    # LLM backend
    lines.append(f"[bold]LLM Backend:[/bold] {status['backend']}")
    lines.append(f"[bold]Model:[/bold] {status['model']}")

    # Workers
    lines.append(f"[bold]Max Workers:[/bold] {status['max_workers']}")

    return "\n".join(lines)


# =============================================================================
# BLOCKLIST MANAGEMENT COMMANDS
# =============================================================================


@osint.group("blocklist")
def blocklist():
    """Manage threat blocklist for OSINT operations.

    The blocklist protects against accessing dangerous sites including:
    - Ransomware infrastructure (LockBit, BlackCat, etc.)
    - Zero-click exploits (Pegasus/NSO Group)
    - Malware distribution and C2 servers
    - Illegal content

    Example:
        groknroll osint blocklist status
        groknroll osint blocklist update
        groknroll osint blocklist add malware.onion
    """
    pass


@blocklist.command("status")
def blocklist_status():
    """Show blocklist status and statistics.

    Displays:
    - Total blocked entries
    - Entries by category and severity
    - Custom entries count
    - Enabled threat feeds
    - Last update time

    Example:
        groknroll osint blocklist status
    """
    from groknroll.osint.blocklist import get_blocklist_manager

    try:
        manager = get_blocklist_manager()
        stats = manager.get_stats()
        feeds = manager.list_feeds()

        # Status panel
        console.print()
        console.print(
            Panel.fit(
                f"[bold]Total Entries:[/bold] {stats['total_entries']}\n"
                f"[bold]Custom Entries:[/bold] {stats['custom_entries']}\n"
                f"[bold]Enabled Feeds:[/bold] {stats['enabled_feeds']}\n"
                f"[bold]Last Update:[/bold] {stats.get('last_feed_update') or 'Never'}",
                title="[bold cyan]Blocklist Status[/bold cyan]",
                border_style="cyan",
            )
        )

        # By category
        console.print("\n[bold]Entries by Category:[/bold]")
        table = Table()
        table.add_column("Category", style="cyan")
        table.add_column("Count", justify="right", style="green")

        for category, count in sorted(stats["by_category"].items()):
            table.add_row(category, str(count))

        console.print(table)

        # By severity
        console.print("\n[bold]Entries by Severity:[/bold]")
        severity_table = Table()
        severity_table.add_column("Severity", style="cyan")
        severity_table.add_column("Count", justify="right", style="green")

        severity_colors = {
            "critical": "red",
            "high": "yellow",
            "medium": "blue",
            "low": "dim",
        }

        for severity, count in sorted(stats["by_severity"].items()):
            color = severity_colors.get(severity, "white")
            severity_table.add_row(f"[{color}]{severity}[/{color}]", str(count))

        console.print(severity_table)

        # Feeds status
        console.print("\n[bold]Threat Feeds:[/bold]")
        for name, info in feeds["feeds"].items():
            status_icon = "[green]✓[/green]" if info["enabled"] else "[dim]○[/dim]"
            console.print(f"  {status_icon} {name}")

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@blocklist.command("update")
@click.option(
    "--feed",
    "-f",
    multiple=True,
    help="Specific feed to update (can be repeated)",
)
@click.option(
    "--all",
    "update_all",
    is_flag=True,
    help="Update all enabled feeds",
)
def blocklist_update(feed: tuple[str, ...], update_all: bool):
    """Update blocklist from threat intelligence feeds.

    Downloads latest threat data from enabled feeds:
    - hagezi_threat: HaGeZi DNS blocklist (600k+ domains)
    - abuse_urlhaus: URLhaus malware URLs
    - cyberhost_malware: CyberHost malware list

    Example:
        groknroll osint blocklist update --all
        groknroll osint blocklist update --feed hagezi_threat
    """
    from groknroll.osint.blocklist import get_blocklist_manager

    try:
        manager = get_blocklist_manager()

        with Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            console=console,
        ) as progress:
            if update_all or not feed:
                task = progress.add_task("Updating all enabled feeds...", total=None)
                results = manager.update_all_feeds()
            else:
                results = []
                for feed_name in feed:
                    task = progress.add_task(f"Updating {feed_name}...", total=None)
                    result = manager.update_feed(feed_name)
                    results.append(result)
                    progress.update(task, completed=True)

        # Display results
        console.print()

        success_count = 0
        total_added = 0

        for result in results:
            if result["success"]:
                success_count += 1
                total_added += result["added"]
                console.print(
                    f"[green]✓[/green] {result['feed']}: {result['added']} entries added"
                )
            else:
                console.print(
                    f"[red]✗[/red] {result['feed']}: {result.get('error', 'Unknown error')}"
                )

        console.print(
            f"\n[bold]Summary:[/bold] {success_count}/{len(results)} feeds updated, "
            f"{total_added} total entries added"
        )

        # Save
        manager.save()

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@blocklist.command("add")
@click.argument("domain")
@click.option(
    "--category",
    "-c",
    default="malware_distribution",
    help="Threat category",
    show_default=True,
)
@click.option(
    "--severity",
    "-s",
    type=click.Choice(["critical", "high", "medium", "low"]),
    default="medium",
    help="Threat severity",
    show_default=True,
)
@click.option(
    "--description",
    "-d",
    default="",
    help="Description of the threat",
)
@click.option(
    "--actor",
    "-a",
    default=None,
    help="Associated threat actor",
)
def blocklist_add(
    domain: str,
    category: str,
    severity: str,
    description: str,
    actor: Optional[str],
):
    """Add a domain to the custom blocklist.

    Manually block a domain for OSINT searches. Use 'regex:' prefix
    for pattern matching.

    Example:
        groknroll osint blocklist add malware.onion
        groknroll osint blocklist add "regex:lockbit.*\\.onion" -c ransomware_infrastructure -s critical
        groknroll osint blocklist add evil.onion -a "ThreatActor" -d "Known C2 server"
    """
    from groknroll.osint.blocklist import get_blocklist_manager

    try:
        manager = get_blocklist_manager()

        success = manager.add_custom_domain(
            domain=domain,
            category=category,
            severity=severity,
            description=description,
            threat_actor=actor,
        )

        if success:
            manager.save()
            console.print(f"[green]✓[/green] Added '{domain}' to blocklist")
            console.print(f"  Category: {category}")
            console.print(f"  Severity: {severity}")
            if actor:
                console.print(f"  Actor: {actor}")
        else:
            console.print(f"[red]✗[/red] Failed to add '{domain}'")
            sys.exit(1)

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@blocklist.command("remove")
@click.argument("domain")
def blocklist_remove(domain: str):
    """Remove a domain from the custom blocklist.

    Note: Only removes custom entries, not built-in threat intelligence.

    Example:
        groknroll osint blocklist remove example.onion
    """
    from groknroll.osint.blocklist import get_blocklist_manager

    try:
        manager = get_blocklist_manager()

        if manager.remove_domain(domain):
            manager.save()
            console.print(f"[green]✓[/green] Removed '{domain}' from blocklist")
        else:
            console.print(f"[yellow]![/yellow] '{domain}' not found in custom blocklist")
            console.print("[dim]Note: Built-in entries cannot be removed[/dim]")

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@blocklist.command("check")
@click.argument("url")
def blocklist_check(url: str):
    """Check if a URL is blocked.

    Tests a URL against the blocklist and shows threat details if blocked.

    Example:
        groknroll osint blocklist check "http://suspicious.onion"
    """
    from groknroll.osint.blocklist import get_blocklist_manager

    try:
        manager = get_blocklist_manager()
        result = manager.check_url(url)

        console.print()

        if result:
            console.print(f"[bold red]⚠ BLOCKED[/bold red]: {url}\n")

            table = Table(show_header=False)
            table.add_column("Field", style="cyan")
            table.add_column("Value")

            table.add_row("Category", result["category"])
            table.add_row("Severity", result["severity"])
            table.add_row("Description", result["description"])
            table.add_row("Source", result.get("source", "unknown"))

            if result.get("threat_actor"):
                table.add_row("Threat Actor", result["threat_actor"])

            console.print(table)
        else:
            console.print(f"[green]✓ SAFE[/green]: {url}")
            console.print("[dim]URL not found in blocklist[/dim]")

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@blocklist.command("list")
@click.option(
    "--custom",
    "show_custom",
    is_flag=True,
    help="Show only custom entries",
)
@click.option(
    "--category",
    "-c",
    default=None,
    help="Filter by category",
)
@click.option(
    "--actor",
    "-a",
    default=None,
    help="Filter by threat actor",
)
@click.option(
    "--limit",
    "-l",
    default=50,
    type=int,
    help="Maximum entries to show",
    show_default=True,
)
def blocklist_list(
    show_custom: bool,
    category: Optional[str],
    actor: Optional[str],
    limit: int,
):
    """List blocklist entries.

    Example:
        groknroll osint blocklist list --custom
        groknroll osint blocklist list --category ransomware_infrastructure
        groknroll osint blocklist list --actor "LockBit" --limit 20
    """
    from groknroll.osint.blocklist import ThreatCategory, get_blocklist_manager

    try:
        manager = get_blocklist_manager()

        if show_custom:
            entries = manager.list_custom_entries()
        elif category:
            try:
                cat = ThreatCategory(category)
                entries = [
                    e.to_dict()
                    for e in manager.blocklist.get_domains_by_category(cat)
                ]
            except ValueError:
                console.print(f"[red]Unknown category: {category}[/red]")
                console.print(
                    f"[dim]Available: {[c.value for c in ThreatCategory]}[/dim]"
                )
                sys.exit(1)
        elif actor:
            entries = [
                e.to_dict()
                for e in manager.blocklist.get_domains_by_actor(actor)
            ]
        else:
            entries = manager.list_custom_entries()
            show_custom = True  # Default to custom

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

        # Display
        table = Table(title=f"Blocklist Entries ({'Custom' if show_custom else 'Filtered'})")
        table.add_column("Domain", style="cyan", max_width=40)
        table.add_column("Category", style="dim")
        table.add_column("Severity")
        table.add_column("Actor", style="yellow")

        severity_colors = {
            "critical": "red",
            "high": "yellow",
            "medium": "blue",
            "low": "dim",
        }

        for entry in entries[:limit]:
            sev = entry.get("severity", "medium")
            color = severity_colors.get(sev, "white")

            table.add_row(
                entry.get("domain", "")[:40],
                entry.get("category", ""),
                f"[{color}]{sev}[/{color}]",
                entry.get("threat_actor") or "",
            )

        console.print()
        console.print(table)

        if len(entries) > limit:
            console.print(f"\n[dim]Showing {limit} of {len(entries)} entries[/dim]")

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@blocklist.command("actors")
def blocklist_actors():
    """List tracked threat actors.

    Shows all threat actors with entries in the blocklist.

    Example:
        groknroll osint blocklist actors
    """
    from groknroll.osint.blocklist import get_blocklist_manager

    try:
        manager = get_blocklist_manager()
        actors = manager.blocklist.get_threat_actors()

        if not actors:
            console.print("[yellow]No threat actors tracked[/yellow]")
            return

        console.print()
        console.print("[bold]Tracked Threat Actors:[/bold]\n")

        for actor in actors:
            domains = manager.blocklist.get_domains_by_actor(actor)
            console.print(f"  • {actor} ({len(domains)} entries)")

        console.print(f"\n[dim]Total: {len(actors)} actors[/dim]")

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@blocklist.command("feeds")
def blocklist_feeds():
    """List available threat intelligence feeds.

    Shows all feeds with their status (enabled/disabled).

    Example:
        groknroll osint blocklist feeds
    """
    from groknroll.osint.blocklist import get_blocklist_manager

    try:
        manager = get_blocklist_manager()
        feeds_info = manager.list_feeds()

        console.print()

        table = Table(title="Threat Intelligence Feeds")
        table.add_column("Feed", style="cyan")
        table.add_column("Status")
        table.add_column("URL", style="dim", max_width=50)

        for name, info in feeds_info["feeds"].items():
            status = "[green]Enabled[/green]" if info["enabled"] else "[dim]Disabled[/dim]"
            url = info["url"][:50] + "..." if len(info["url"]) > 50 else info["url"]
            table.add_row(name, status, url)

        console.print(table)

        if feeds_info.get("last_update"):
            console.print(f"\n[dim]Last update: {feeds_info['last_update']}[/dim]")

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@blocklist.command("enable-feed")
@click.argument("feed_name")
def blocklist_enable_feed(feed_name: str):
    """Enable a threat feed for updates.

    Example:
        groknroll osint blocklist enable-feed cyberhost_malware
    """
    from groknroll.osint.blocklist import get_blocklist_manager

    try:
        manager = get_blocklist_manager()

        if manager.enable_feed(feed_name):
            manager.save()
            console.print(f"[green]✓[/green] Enabled feed: {feed_name}")
        else:
            console.print(f"[red]✗[/red] Unknown feed: {feed_name}")
            console.print("[dim]Use 'groknroll osint blocklist feeds' to see available feeds[/dim]")
            sys.exit(1)

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@blocklist.command("disable-feed")
@click.argument("feed_name")
def blocklist_disable_feed(feed_name: str):
    """Disable a threat feed.

    Example:
        groknroll osint blocklist disable-feed abuse_feodo
    """
    from groknroll.osint.blocklist import get_blocklist_manager

    try:
        manager = get_blocklist_manager()

        if manager.disable_feed(feed_name):
            manager.save()
            console.print(f"[green]✓[/green] Disabled feed: {feed_name}")
        else:
            console.print(f"[yellow]![/yellow] Feed '{feed_name}' was not enabled")

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@blocklist.command("import")
@click.argument("file_path", type=click.Path(exists=True))
def blocklist_import(file_path: str):
    """Import blocklist from file.

    Supports JSON and plain text (one domain per line) formats.

    Example:
        groknroll osint blocklist import custom_blocklist.json
        groknroll osint blocklist import domains.txt
    """
    from groknroll.osint.blocklist import get_blocklist_manager

    try:
        manager = get_blocklist_manager()

        with Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            console=console,
        ) as progress:
            task = progress.add_task(f"Importing from {file_path}...", total=None)
            result = manager.import_blocklist(Path(file_path))

        if result["success"]:
            manager.save()
            console.print(f"[green]✓[/green] Imported {result['imported']} entries")
        else:
            console.print(f"[red]✗[/red] Import failed: {result.get('error')}")
            sys.exit(1)

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@blocklist.command("export")
@click.argument("output_path", type=click.Path())
@click.option(
    "--full",
    is_flag=True,
    help="Include feed-sourced entries (not just custom)",
)
def blocklist_export(output_path: str, full: bool):
    """Export blocklist to file.

    Default exports only custom entries. Use --full for complete blocklist.

    Example:
        groknroll osint blocklist export my_blocklist.json
        groknroll osint blocklist export full_blocklist.json --full
    """
    from groknroll.osint.blocklist import get_blocklist_manager

    try:
        manager = get_blocklist_manager()

        if manager.export_blocklist(Path(output_path), include_feeds=full):
            console.print(f"[green]✓[/green] Exported to {output_path}")
            if full:
                stats = manager.get_stats()
                console.print(f"[dim]Total entries: {stats['total_entries']}[/dim]")
        else:
            console.print("[red]✗[/red] Export failed")
            sys.exit(1)

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)
