#!/usr/bin/env python3
"""
souleyez.handlers.lfi_extract_handler - Handler for LFI credential extraction

Parses LFI extract results and stores discovered credentials in the database.
"""

import json
import logging
import os
import re
from typing import Any, Dict, List, Optional

import click

from souleyez.engine.job_status import STATUS_DONE, STATUS_ERROR, STATUS_NO_RESULTS
from souleyez.handlers.base import BaseToolHandler

logger = logging.getLogger(__name__)


class LfiExtractHandler(BaseToolHandler):
    """Handler for LFI Extract custom tool."""

    tool_name = "lfi_extract"
    display_name = "LFI Extract"

    # All handlers enabled
    has_error_handler = True
    has_warning_handler = True
    has_no_results_handler = True
    has_done_handler = True

    def parse_job(
        self,
        engagement_id: int,
        log_path: str,
        job: Dict[str, Any],
        host_manager: Optional[Any] = None,
        findings_manager: Optional[Any] = None,
        credentials_manager: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """
        Parse LFI extract job results.

        Extracts credentials from the JSON result and stores them in the database.
        """
        try:
            # Guard against empty output
            if not os.path.exists(log_path) or os.path.getsize(log_path) == 0:
                return {
                    "tool": self.tool_name,
                    "status": STATUS_NO_RESULTS,
                    "summary": "Empty output (tool produced no output)",
                }

            from souleyez.engine.result_handler import detect_tool_error

            # Import managers if not provided
            if host_manager is None:
                from souleyez.storage.hosts import HostManager

                host_manager = HostManager()
            if findings_manager is None:
                from souleyez.storage.findings import FindingsManager

                findings_manager = FindingsManager()
            if credentials_manager is None:
                from souleyez.storage.credentials import CredentialsManager

                credentials_manager = CredentialsManager()

            # Read log file
            if not log_path or not os.path.exists(log_path):
                return {
                    "error": "Log file not found",
                    "status": STATUS_ERROR,
                    "summary": "Log file not found",
                }

            with open(log_path, "r", encoding="utf-8", errors="replace") as f:
                log_content = f.read()

            # Generic error detection (supplement to handler-specific checks)
            tool_error = detect_tool_error(log_content, "lfi_extract")

            # Extract JSON result
            json_match = re.search(
                r"=== JSON_RESULT ===\s*\n(.*?)\n=== END_JSON_RESULT ===",
                log_content,
                re.DOTALL,
            )

            if not json_match:
                error_msg = tool_error or "No JSON result found in log"
                return {
                    "error": error_msg,
                    "status": STATUS_ERROR,
                    "summary": (
                        f"Tool error: {error_msg}"
                        if tool_error
                        else "Failed to parse output"
                    ),
                }

            try:
                result = json.loads(json_match.group(1))
            except json.JSONDecodeError as e:
                return {
                    "error": f"Failed to parse JSON result: {e}",
                    "status": STATUS_ERROR,
                    "summary": "Failed to parse output",
                }

            credentials = result.get("credentials", [])

            if not credentials:
                files_decoded = result.get("decoded_files", [])
                if files_decoded:
                    summary = f"Decoded {len(files_decoded)} file{'s' if len(files_decoded) != 1 else ''}, no credentials found"
                    return {
                        "tool": "lfi_extract",
                        "status": STATUS_NO_RESULTS,
                        "sources_processed": result.get("sources_processed", 0),
                        "sources_failed": result.get("sources_failed", 0),
                        "credentials_found": 0,
                        "decoded_files": files_decoded,
                        "summary": summary,
                    }
                elif tool_error:
                    return {
                        "tool": self.tool_name,
                        "status": STATUS_ERROR,
                        "target": job.get("target", ""),
                        "error": tool_error,
                        "summary": f"Tool error: {tool_error}",
                    }
                else:
                    summary = "No files decoded, no credentials found"
                    return {
                        "tool": "lfi_extract",
                        "status": STATUS_NO_RESULTS,
                        "sources_processed": result.get("sources_processed", 0),
                        "sources_failed": result.get("sources_failed", 0),
                        "credentials_found": 0,
                        "decoded_files": files_decoded,
                        "summary": summary,
                    }

            # Get or create host from target URL
            target = job.get("target", "")
            host_id = None

            if target:
                from urllib.parse import urlparse

                parsed_url = urlparse(target)
                target_host = parsed_url.hostname or target

                host_result = host_manager.add_or_update_host(
                    engagement_id, {"ip": target_host, "status": "up"}
                )
                if isinstance(host_result, dict):
                    host_id = host_result.get("id")
                else:
                    host_id = host_result

            # Store credentials and create findings
            stored_credentials = []

            for cred in credentials:
                cred_type = cred.get("credential_type", "unknown")

                if cred_type == "database":
                    # Store database credential
                    try:
                        cred_id = credentials_manager.add_credential(
                            engagement_id=engagement_id,
                            host_id=host_id,
                            username=cred.get("username"),
                            password=cred.get("password"),
                            service=cred.get("database", "mysql"),
                            credential_type="database",
                            status="untested",
                            tool="lfi_extract",
                        )
                        stored_credentials.append(
                            {
                                "id": cred_id,
                                "type": "database",
                                "username": cred.get("username"),
                                "password": cred.get("password"),
                                "credential_type": "database",
                            }
                        )

                        # Create critical finding
                        findings_manager.add_finding(
                            engagement_id=engagement_id,
                            host_id=host_id,
                            title=f"LFI Credential Extraction: {cred.get('username')}@{cred.get('database', 'database')}",
                            finding_type="credential",
                            severity="critical",
                            description=(
                                f"Database credentials extracted via LFI vulnerability:\n\n"
                                f"**Username:** {cred.get('username')}\n"
                                f"**Database:** {cred.get('database', 'unknown')}\n"
                                f"**Host:** {cred.get('host', 'localhost')}\n\n"
                                f"**Source File:** {cred.get('source_file', 'unknown')}\n"
                                f"**Source URL:** {cred.get('source_url', 'unknown')}\n\n"
                                f"This indicates a critical LFI vulnerability that exposes database credentials. "
                                f"The attacker can now attempt to access the database directly."
                            ),
                            tool="lfi_extract",
                        )
                        logger.info(
                            f"Stored database credential: {cred.get('username')}@{cred.get('database')}"
                        )

                    except Exception as e:
                        logger.warning(f"Failed to store credential: {e}")

                elif cred_type in ("api_key", "secret_key"):
                    # Store API key as credential
                    try:
                        api_key = cred.get("api_key", "")
                        cred_id = credentials_manager.add_credential(
                            engagement_id=engagement_id,
                            host_id=host_id,
                            username=cred_type,
                            password=api_key,
                            service="api",
                            credential_type=cred_type,
                            status="untested",
                            tool="lfi_extract",
                        )
                        stored_credentials.append(
                            {
                                "id": cred_id,
                                "type": cred_type,
                                "credential_type": cred_type,
                            }
                        )

                        # Create finding for API key
                        findings_manager.add_finding(
                            engagement_id=engagement_id,
                            host_id=host_id,
                            title=f"LFI Exposed {cred_type.replace('_', ' ').title()}",
                            finding_type="credential",
                            severity="high",
                            description=(
                                f"API key/secret extracted via LFI vulnerability:\n\n"
                                f"**Type:** {cred_type}\n"
                                f"**Key (truncated):** {api_key[:20]}...{api_key[-10:] if len(api_key) > 30 else ''}\n\n"
                                f"**Source File:** {cred.get('source_file', 'unknown')}\n"
                                f"**Source URL:** {cred.get('source_url', 'unknown')}\n\n"
                                f"This key may provide access to external services or APIs."
                            ),
                            tool="lfi_extract",
                        )
                        logger.info(f"Stored {cred_type}")

                    except Exception as e:
                        logger.warning(f"Failed to store API key: {e}")

            # Build summary for UI display
            cred_count = len(stored_credentials)
            files_decoded = result.get("decoded_files", [])
            if cred_count > 0:
                summary = f"Extracted {cred_count} credential{'s' if cred_count != 1 else ''} from {len(files_decoded)} file{'s' if len(files_decoded) != 1 else ''}"
            elif files_decoded:
                summary = f"Decoded {len(files_decoded)} file{'s' if len(files_decoded) != 1 else ''}, no credentials found"
            else:
                summary = "No files decoded"

            return {
                "tool": "lfi_extract",
                "status": STATUS_DONE,
                "sources_processed": result.get("sources_processed", 0),
                "sources_failed": result.get("sources_failed", 0),
                "credentials_found": cred_count,
                "credentials": stored_credentials,
                "decoded_files": files_decoded,
                "summary": summary,
            }

        except Exception as e:
            logger.error(f"Error parsing lfi_extract job: {e}")
            return {
                "tool": self.tool_name,
                "status": STATUS_ERROR,
                "error": str(e),
                "summary": f"Parse error: {e}",
            }

    def display_done(
        self,
        job: Dict[str, Any],
        log_path: str,
        show_all: bool = False,
        show_passwords: bool = False,
    ) -> None:
        """Display successful LFI extract results."""
        try:
            if not log_path or not os.path.exists(log_path):
                return

            with open(log_path, "r", encoding="utf-8", errors="replace") as f:
                log_content = f.read()

            # Extract JSON result
            json_match = re.search(
                r"=== JSON_RESULT ===\s*\n(.*?)\n=== END_JSON_RESULT ===",
                log_content,
                re.DOTALL,
            )

            if not json_match:
                click.echo("No results to display.")
                return

            result = json.loads(json_match.group(1))
            credentials = result.get("credentials", [])

            click.echo(click.style("=" * 70, fg="green"))
            click.echo(
                click.style("LFI EXTRACT - CREDENTIALS FOUND", bold=True, fg="green")
            )
            click.echo(click.style("=" * 70, fg="green"))
            click.echo()
            click.echo(f"  Sources processed: {result.get('sources_processed', 0)}")
            click.echo(
                f"  Files decoded: {', '.join(result.get('decoded_files', [])) or 'None'}"
            )
            click.echo()

            if credentials:
                click.echo(click.style("-" * 40, fg="green"))
                click.echo(click.style("EXTRACTED CREDENTIALS:", bold=True, fg="green"))
                click.echo(click.style("-" * 40, fg="green"))
                click.echo()

                for i, cred in enumerate(credentials, 1):
                    cred_type = cred.get("credential_type", "unknown")

                    if cred_type == "database":
                        click.echo(
                            click.style(
                                f"  [{i}] DATABASE CREDENTIALS", bold=True, fg="yellow"
                            )
                        )
                        click.echo(f"      Username: {cred.get('username')}")
                        if show_passwords:
                            click.echo(f"      Password: {cred.get('password')}")
                        else:
                            click.echo(
                                f"      Password: {'*' * 8} (use --show-passwords to reveal)"
                            )
                        click.echo(f"      Database: {cred.get('database', 'unknown')}")
                        click.echo(f"      Host: {cred.get('host', 'localhost')}")
                        click.echo(
                            f"      Source: {cred.get('source_file', 'unknown')}"
                        )

                    elif cred_type in ("api_key", "secret_key"):
                        click.echo(
                            click.style(
                                f"  [{i}] {cred_type.upper()}", bold=True, fg="yellow"
                            )
                        )
                        api_key = cred.get("api_key", "")
                        if show_passwords:
                            click.echo(f"      Key: {api_key}")
                        else:
                            click.echo(
                                f"      Key: {api_key[:10]}...{api_key[-5:] if len(api_key) > 15 else ''}"
                            )
                        click.echo(
                            f"      Source: {cred.get('source_file', 'unknown')}"
                        )

                    click.echo()

                click.echo(click.style("-" * 40, fg="cyan"))
                click.echo(click.style("NEXT STEPS:", bold=True, fg="cyan"))
                click.echo(click.style("-" * 40, fg="cyan"))
                click.echo("  1. Test database credentials against MySQL/PostgreSQL")
                click.echo(
                    "  2. Check if credentials work on other services (SSH, FTP)"
                )
                click.echo("  3. Use 'souleyez creds list' to view all credentials")
                click.echo("  4. Chain to Hydra for credential spraying")
                click.echo()

            click.echo(click.style("=" * 70, fg="green"))
            click.echo()

        except Exception as e:
            logger.debug(f"Error in display_done: {e}")

    def display_error(
        self,
        job: Dict[str, Any],
        log_path: str,
        log_content: Optional[str] = None,
    ) -> None:
        """Display error status for LFI extract."""
        click.echo(click.style("=" * 70, fg="red"))
        click.echo(click.style("[ERROR] LFI EXTRACT FAILED", bold=True, fg="red"))
        click.echo(click.style("=" * 70, fg="red"))
        click.echo()

        if log_content is None and log_path and os.path.exists(log_path):
            try:
                with open(log_path, "r", encoding="utf-8", errors="replace") as f:
                    log_content = f.read()
            except Exception:
                log_content = ""

        if log_content:
            # Look for error messages
            if "Error:" in log_content:
                match = re.search(r"Error:\s*(.+?)(?:\n|$)", log_content)
                if match:
                    click.echo(f"  Error: {match.group(1)}")
            elif "No PHP filter URLs" in log_content:
                click.echo("  No PHP filter URLs were provided to extract from.")
                click.echo()
                click.echo(
                    click.style("  This tool expects URLs like:", fg="bright_black")
                )
                click.echo(
                    click.style(
                        "    http://target/?page=php://filter/convert.base64-encode/resource=config",
                        fg="bright_black",
                    )
                )
            else:
                click.echo("  Extraction failed - see raw logs for details.")
                click.echo("  Press [r] to view raw logs.")

        click.echo()
        click.echo(click.style("=" * 70, fg="red"))
        click.echo()

    def display_no_results(
        self,
        job: Dict[str, Any],
        log_path: str,
    ) -> None:
        """Display no_results status for LFI extract."""
        click.echo(click.style("=" * 70, fg="cyan"))
        click.echo(
            click.style("LFI EXTRACT - NO CREDENTIALS FOUND", bold=True, fg="cyan")
        )
        click.echo(click.style("=" * 70, fg="cyan"))
        click.echo()
        click.echo("  The PHP source code was decoded but no credentials were found.")
        click.echo()
        click.echo(click.style("  This could mean:", fg="bright_black"))
        click.echo(
            click.style(
                "    - Config file doesn't contain database credentials",
                fg="bright_black",
            )
        )
        click.echo(
            click.style(
                "    - Credentials use a format not recognized by the parser",
                fg="bright_black",
            )
        )
        click.echo(
            click.style(
                "    - Try targeting different config files (wp-config.php, .env, etc.)",
                fg="bright_black",
            )
        )
        click.echo()
        click.echo(
            click.style(
                "  Check the raw logs for the decoded source code.", fg="bright_black"
            )
        )
        click.echo()
        click.echo(click.style("=" * 70, fg="cyan"))
        click.echo()

    def display_warning(
        self,
        job: Dict[str, Any],
        log_path: str,
        log_content: Optional[str] = None,
    ) -> None:
        """Display warning status for LFI extract."""
        click.echo(click.style("=" * 70, fg="yellow"))
        click.echo(click.style("[WARNING] LFI EXTRACT", bold=True, fg="yellow"))
        click.echo(click.style("=" * 70, fg="yellow"))
        click.echo()
        click.echo("  Extraction completed with warnings. Some URLs may have failed.")
        click.echo("  Press [r] to view raw logs for details.")
        click.echo()
        click.echo(click.style("=" * 70, fg="yellow"))
        click.echo()

    def generate_next_steps(
        self,
        job: Dict[str, Any],
        context: Any,
    ) -> list:
        """
        Generate SMART next steps based on LFI extract results.

        Smart suggestions:
        - Test extracted database credentials
        - Spray credentials on other services
        - Further LFI exploration
        """
        from souleyez.core.next_steps import create_next_step

        steps = []
        parse_result = job.get("parse_result", {})
        if not isinstance(parse_result, dict):
            return steps

        target = job.get("target", "")
        credentials = parse_result.get("credentials", [])
        credentials_found = parse_result.get("credentials_found", 0)
        decoded_files = parse_result.get("decoded_files", [])

        # Extract host from target URL
        host = target
        if "://" in target:
            from urllib.parse import urlparse

            parsed = urlparse(target)
            host = parsed.hostname or target

        if credentials_found > 0:
            # Get first credential for command examples
            first_cred = credentials[0] if credentials else {}
            cred_type = first_cred.get("credential_type") or first_cred.get(
                "type", "unknown"
            )

            if cred_type == "database":
                username = first_cred.get("username", "user")
                password = first_cred.get("password", "")

                # Priority 1: Test database credentials
                steps.append(
                    create_next_step(
                        title="Test extracted database credentials",
                        reason="Database credentials extracted via LFI",
                        commands=[
                            f"# Test MySQL connection:",
                            f"mysql -h {host} -u '{username}' -p'{password[:3] if password else 'PASS'}...'",
                            "",
                            f"# Or use SQLMap to enumerate:",
                            f"sqlmap -d 'mysql://{username}:PASSWORD@{host}/' --dbs",
                        ],
                        priority=1,
                        category="database",
                        target=target,
                        tool="sqlmap",
                    )
                )

                # Priority 2: Spray credentials on other services
                steps.append(
                    create_next_step(
                        title="Test credentials on other services",
                        reason="Database credentials may be reused elsewhere",
                        commands=[
                            f"# Try SSH:",
                            f"ssh {username}@{host}",
                            "",
                            f"# Try FTP:",
                            f"ftp {host} # (use {username})",
                            "",
                            f"# Spray with Hydra:",
                            f"hydra -l {username} -p 'PASSWORD' {host} ssh",
                        ],
                        priority=2,
                        category="credential",
                        target=target,
                        tool="hydra",
                    )
                )

            elif cred_type in ("api_key", "secret_key"):
                # Priority 1: Research API key type
                steps.append(
                    create_next_step(
                        title="Identify and abuse API key",
                        reason="API key extracted - determine its service",
                        commands=[
                            "# Check key format to identify service:",
                            "# AWS: AKIA...",
                            "# Google: AIza...",
                            "# Stripe: sk_live_...",
                            "",
                            "# Search decoded files for API endpoints",
                        ],
                        priority=1,
                        category="api",
                        target=target,
                        tool="manual",
                    )
                )

        # Decoded files but no creds - suggest searching content
        if decoded_files and credentials_found == 0:
            steps.append(
                create_next_step(
                    title="Manually search decoded files for secrets",
                    reason=f"Decoded {len(decoded_files)} files - may contain hardcoded secrets",
                    commands=[
                        "# View raw logs to see decoded source:",
                        "# Search for patterns like:",
                        "grep -i 'password\\|secret\\|key\\|token' decoded_files",
                        "",
                        "# Common config patterns:",
                        "grep -i 'db_\\|mysql_\\|api_' decoded_files",
                    ],
                    priority=2,
                    category="analysis",
                    target=target,
                    tool="manual",
                )
            )

        # Priority 3: Try more LFI targets
        steps.append(
            create_next_step(
                title="Explore more files via LFI",
                reason="LFI confirmed - extract more sensitive files",
                commands=[
                    "# Common targets:",
                    f"# /etc/passwd",
                    f"# /etc/shadow (if root)",
                    f"# /proc/self/environ",
                    f"# ~/.ssh/id_rsa",
                    "",
                    "# WordPress: wp-config.php",
                    "# Laravel: .env",
                    "# PHP: config.php, database.php",
                ],
                priority=3,
                category="enumeration",
                target=target,
                tool="lfi_extract",
            )
        )

        return steps[:10]


# Register handler
handler = LfiExtractHandler()
