"""Core conversion logic for HWP to Markdown."""

import subprocess
import sys
import shutil
from pathlib import Path
from typing import Optional, List, Tuple


def check_command(cmd: str) -> bool:
    """Check if a command is available."""
    return shutil.which(cmd) is not None


def check_dependencies() -> dict:
    """Check if required dependencies are installed."""
    return {
        "hwp5html": check_command("hwp5html"),
        "html2text": check_command("html2text"),
    }


def install_dependencies():
    """Install required Python dependencies."""
    print("Installing dependencies...")
    subprocess.run([sys.executable, "-m", "pip", "install", "pyhwp", "html2text"], check=True)
    print("✓ Dependencies installed")


def hwp_to_html(input_path: Path, output_dir: Path) -> Path:
    """Convert HWP to HTML using hwp5html."""
    output_dir.mkdir(parents=True, exist_ok=True)

    result = subprocess.run(
        ["hwp5html", str(input_path), "--output", str(output_dir)],
        capture_output=True,
        text=True
    )

    if result.returncode != 0:
        if "error" in result.stderr.lower() and "undefined" not in result.stderr.lower():
            raise RuntimeError(f"hwp5html failed: {result.stderr}")

    index_path = output_dir / "index.xhtml"
    if not index_path.exists():
        raise FileNotFoundError(f"HTML output not found: {index_path}")

    return index_path


def html_to_markdown(html_path: Path, output_path: Path):
    """Convert HTML to Markdown using html2text."""
    result = subprocess.run(
        ["html2text", str(html_path)],
        capture_output=True,
        text=True
    )

    if result.returncode != 0:
        raise RuntimeError(f"html2text failed: {result.stderr}")

    output_path.write_text(result.stdout, encoding="utf-8")


def convert_hwp(
    input_path: Path,
    output_path: Optional[Path] = None,
    keep_html: bool = False
) -> Tuple[bool, str]:
    """
    Convert a single HWP file to Markdown.

    Args:
        input_path: Path to HWP file
        output_path: Output markdown path (default: same name with .md)
        keep_html: Keep intermediate HTML files

    Returns:
        Tuple of (success, message)
    """
    input_path = Path(input_path)

    if output_path is None:
        output_path = input_path.with_suffix(".md")
    else:
        output_path = Path(output_path)

    html_dir = input_path.parent / f".{input_path.stem}_html"

    try:
        html_path = hwp_to_html(input_path, html_dir)
        html_to_markdown(html_path, output_path)

        if not keep_html:
            shutil.rmtree(html_dir, ignore_errors=True)

        return True, str(output_path)

    except Exception as e:
        if html_dir.exists() and not keep_html:
            shutil.rmtree(html_dir, ignore_errors=True)
        return False, str(e)


def batch_convert(
    input_dir: Path,
    output_dir: Optional[Path] = None,
    keep_html: bool = False
) -> List[Tuple[Path, bool, str]]:
    """
    Convert all HWP files in a directory.

    Args:
        input_dir: Directory containing HWP files
        output_dir: Output directory (default: input_dir/converted)
        keep_html: Keep intermediate HTML files

    Returns:
        List of (file_path, success, message) tuples
    """
    input_dir = Path(input_dir)

    if output_dir is None:
        output_dir = input_dir / "converted"
    else:
        output_dir = Path(output_dir)

    output_dir.mkdir(parents=True, exist_ok=True)

    hwp_files = list(input_dir.glob("*.hwp")) + list(input_dir.glob("*.HWP"))
    results = []

    for hwp_file in hwp_files:
        output_path = output_dir / hwp_file.with_suffix(".md").name
        print(f"  Converting: {hwp_file.name}")

        success, msg = convert_hwp(hwp_file, output_path, keep_html)
        results.append((hwp_file, success, msg))

        if success:
            print(f"    ✓ {output_path.name}")
        else:
            print(f"    ✗ {msg}")

    return results
