from . import ui
from . import config
import sys
import os
import subprocess
import shutil
from pathlib import Path

def is_ssh_key(filepath):
    """Check if file is an SSH private key by looking at the first line."""
    try:
        with open(filepath, 'r', errors='ignore') as f:
            return "PRIVATE KEY" in f.readline()
    except Exception:
        return False


def detect_input(target):
    """
    Classify the CLI argument as either a raw hash string or a protected file.

    Either returns a tuple: `('hash', hash_string)` for raw hashes

    Or `('file', filepath, extension, john_tool_name)` for files needing extraction
    """
    if not os.path.isfile(target):
        return ('hash', target)

    if is_ssh_key(target):
        return ('file', target, '.ssh', 'ssh2john')

    ext = Path(target).suffix.lower()
    tool = config.FILE_TO_JOHN.get(ext)
    if tool:
        return ('file', target, ext, tool)

    # Maybe it's a text file containing a single hash
    with open(target, 'r', errors='ignore') as f:
        content = f.read().strip()
    if '\n' not in content and len(content) < 200:
        return ('hash', content)

    ui.err(f"File type '{ext}' not recognised. Supported: {list(config.FILE_TO_JOHN.keys())} + SSH keys")
    sys.exit(1)


def extract_hash_from_file(filepath, tool_name):
    """Run a john *2john tool to extract the crackable hash from a file."""
    if not shutil.which(tool_name):
        ui.err(f"'{tool_name}' not found — it should ship with Jumbo John.")
        sys.exit(1)

    ui.info(f"Extracting hash with {tool_name}...")
    result = subprocess.run([tool_name, filepath], capture_output=True, text=True)
    output = result.stdout.strip()
    if not output:
        ui.err(f"{tool_name} produced no output. File may not be password-protected.")
        sys.exit(1)

    hash_file = "/tmp/quinto_extracted.hash"
    with open(hash_file, 'w') as f:
        f.write(output + "\n")
    ui.ok(f"Hash extracted → {hash_file}")
    return hash_file
