"""CLI interface for hwp-to-md."""

import argparse
import sys
from pathlib import Path

from .converter import (
    check_dependencies,
    install_dependencies,
    convert_hwp,
    batch_convert,
)


def main():
    parser = argparse.ArgumentParser(
        description="Convert HWP files to Markdown",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    subparsers = parser.add_subparsers(dest="command", help="Commands")

    # convert command
    convert_parser = subparsers.add_parser("convert", help="Convert HWP to Markdown")
    convert_parser.add_argument("input", help="Input HWP file or directory")
    convert_parser.add_argument("-o", "--output", help="Output file or directory")
    convert_parser.add_argument(
        "-k", "--keep-html", action="store_true", help="Keep intermediate HTML files"
    )

    # check command
    subparsers.add_parser("check", help="Check dependencies")

    # install command
    subparsers.add_parser("install", help="Install dependencies")

    args = parser.parse_args()

    if args.command is None:
        parser.print_help()
        sys.exit(0)

    if args.command == "check":
        print("\n🔍 Checking dependencies...\n")
        deps = check_dependencies()
        print(f"   hwp5html (pyhwp):  {'✓ installed' if deps['hwp5html'] else '✗ missing'}")
        print(f"   html2text:         {'✓ installed' if deps['html2text'] else '✗ missing'}")

        if not all(deps.values()):
            print("\n📦 To install: pip install pyhwp html2text\n")
            sys.exit(1)
        else:
            print("\n✅ All dependencies installed!\n")

    elif args.command == "install":
        install_dependencies()
        print("\n✅ Dependencies installed!\n")

    elif args.command == "convert":
        deps = check_dependencies()
        if not all(deps.values()):
            print("⚠️  Missing dependencies. Installing...")
            install_dependencies()

        input_path = Path(args.input).resolve()

        print("\n📄 HWP to Markdown Converter")
        print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")

        if input_path.is_dir():
            hwp_files = list(input_path.glob("*.hwp")) + list(input_path.glob("*.HWP"))
            print(f"Found {len(hwp_files)} HWP files\n")

            output_dir = Path(args.output).resolve() if args.output else None
            results = batch_convert(input_path, output_dir, args.keep_html)

            success_count = sum(1 for _, success, _ in results if success)
            print(f"\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
            print(f"✅ Done! {success_count}/{len(results)} files converted\n")

        else:
            output_path = Path(args.output).resolve() if args.output else None

            print(f"Input:  {input_path}")
            print(f"Output: {output_path or input_path.with_suffix('.md')}\n")

            print("🔄 Converting...")
            success, msg = convert_hwp(input_path, output_path, args.keep_html)

            if success:
                print("   ✓ HTML extracted")
                print("   ✓ Markdown generated")
                if not args.keep_html:
                    print("   ✓ Cleanup complete")
                print(f"\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
                print(f"✅ Done! Output: {msg}\n")
            else:
                print(f"\n❌ Conversion failed: {msg}")
                sys.exit(1)


if __name__ == "__main__":
    main()
