import os
import sys
import glob
import traceback

from unhwpy import (
    detect_format,
    convert_to_markdown,
    is_distribution,
    parse,
    RenderOptions,
    TableFallback,
)

sys.stdout.reconfigure(encoding="utf-8")


def test_file(file_path):
    print(f"\n{'=' * 50}")
    print(f"Testing file: {os.path.basename(file_path)}")
    print(f"{'=' * 50}")

    if not os.path.exists(file_path):
        print(f"File not found: {file_path}")
        return

    try:
        with open(file_path, "rb") as f:
            data = f.read()
        print(f"Read {len(data)} bytes.")
    except Exception as e:
        print(f"Failed to read file: {e}")
        return

    # Test detection
    print("\n[1] Testing format detection...")
    try:
        fmt = detect_format(data)
        print(f"  -> Detected Format: {fmt}")
    except Exception as e:
        print(f"  -> Detection failed: {e}")

    # Test parse (New API)
    print("\n[2] Testing Document parsing object...", flush=True)
    document = None
    try:
        document = parse(data)
        print(
            f"  -> Parse successful! Document object type: {type(document)}", flush=True
        )
    except ImportError:
        print("  -> 'parse' function not found.", flush=True)
    except Exception as e:
        print(f"  -> Parse failed: {e}", flush=True)

    # Test is_distribution
    print("\n[3] Testing is_distribution...")
    if is_distribution:
        try:
            # Test with bytes
            is_dist_bytes = is_distribution(data=data)
            print(f"  -> [Bytes] Is Distribution: {is_dist_bytes}")

            # Test with document object
            if document:
                is_dist_doc = is_distribution(document=document)
                print(f"  -> [Document] Is Distribution: {is_dist_doc}")
                assert is_dist_bytes == is_dist_doc, (
                    "Mismatch between bytes and document result"
                )
        except Exception as e:
            print(f"  -> Check failed: {e}")
    else:
        print("  -> Skipped (is_distribution not available in this build)")

    # Test conversion
    print("\n[4] Testing conversion...")
    try:
        options = RenderOptions(table_fallback=TableFallback.Html)
        print("  -> Using options: TableFallback.Html")

        # Test with document object if available
        if document:
            markdown = convert_to_markdown(document=document, options=options)
            print("  -> [Document] Conversion successful (TableFallback.Html)!")
        else:
            markdown = convert_to_markdown(data=data, options=options)
            print("  -> [Bytes] Conversion successful (TableFallback.Html)!")

        # Save to file
        output_path = os.path.splitext(file_path)[0] + ".md"
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(markdown)
        print(f"  -> Saved to: {output_path}")

        preview = markdown[:1000].replace("\n", " ")
        print(f"  -> Preview: {preview}...")
    except Exception as e:
        print(f"  -> Conversion failed: {e}")
        traceback.print_exc()


def main():
    # Get absolute path relative to this script
    current_dir = os.path.dirname(os.path.abspath(__file__))
    test_files_dir = os.path.join(current_dir, "examples", "files")

    # Also check 'files' directory
    files_dir = os.path.join(current_dir, "files")

    files_to_test = []

    if os.path.exists(test_files_dir):
        files_to_test.extend(glob.glob(os.path.join(test_files_dir, "*.hwp")))
        files_to_test.extend(glob.glob(os.path.join(test_files_dir, "*.hwpx")))

    if os.path.exists(files_dir):
        files_to_test.extend(glob.glob(os.path.join(files_dir, "*.hwp")))
        files_to_test.extend(glob.glob(os.path.join(files_dir, "*.hwpx")))

    # Remove duplicates
    files_to_test = list(set(files_to_test))

    if not files_to_test:
        print("No test files found in examples/files or files directories.")
        return

    print(f"Found {len(files_to_test)} files to test.")
    for file_path in files_to_test:
        test_file(file_path)


if __name__ == "__main__":
    main()
