TOOL_NAME = "move_pdfs"
TOOL_DESCRIPTION = """Create a subfolder (default "pdf") in the given source directory and move all PDF files into it."""
TOOL_ARGS = '{"source_dir": "string", "subfolder_name": "string"}'

import os
import shutil

from tools._std import tool_error, tool_ok

def run(args: dict) -> str:
    source_dir = args.get('source_dir')
    subfolder_name = args.get('subfolder_name', 'pdf')
    if not source_dir:
        return tool_error('source_dir not provided.')
    if not os.path.isdir(source_dir):
        return tool_error(
            f'Source directory {source_dir} does not exist.',
            {'source_dir': source_dir},
        )
    subfolder_path = os.path.join(source_dir, subfolder_name)
    try:
        os.makedirs(subfolder_path, exist_ok=True)
    except Exception as e:
        return tool_error(
            f'Error creating subfolder: {e}',
            {'source_dir': source_dir, 'subfolder_name': subfolder_name},
        )
    moved = 0
    moved_files = []
    for item in os.listdir(source_dir):
        if item.lower().endswith('.pdf'):
            src_path = os.path.join(source_dir, item)
            dst_path = os.path.join(subfolder_path, item)
            try:
                shutil.move(src_path, dst_path)
                moved += 1
                moved_files.append(item)
            except Exception as e:
                return tool_error(
                    f'Error moving file {item}: {e}',
                    {'source_dir': source_dir, 'destination_dir': subfolder_path, 'file': item},
                )
    if moved == 0:
        return tool_ok(
            {'source_dir': source_dir, 'destination_dir': subfolder_path, 'moved_count': 0, 'files': []},
            f'No PDF files found in {source_dir}.',
        )
    return tool_ok(
        {
            'source_dir': source_dir,
            'destination_dir': subfolder_path,
            'moved_count': moved,
            'files': moved_files,
        },
        f'Successfully moved {moved} PDF file(s) to {subfolder_path}.',
    )
