from pathlib import Path

from c2m_by_nery.core.config import ConfigError, ConfigManager
from c2m_by_nery.core.pipeline import run_conversion, run_single_file_conversion


def convert_to_markdown(
    root: Path | str,
    *,
    output_dir: str | None = None,
    token_limit: int | None = None,
    frontmatter: bool = True,
    quiet: bool = False,
    verbose: bool = False,
    zip_output: bool = False,
    flat_output: bool | None = None,
    single_file: bool | None = None,
) -> dict:
    root_path = Path(root).resolve()
    config = ConfigManager.load(root_path)
    output_path = output_dir if output_dir is not None else config.output_path
    config = ConfigManager(
        token_limit=token_limit if token_limit is not None else config.token_limit,
        output_path=output_path,
        ignore_patterns=config.ignore_patterns,
        flat_output=flat_output if flat_output is not None else config.flat_output,
        single_file=single_file if single_file is not None else config.single_file,
    )
    return run_conversion(
        root_path,
        config,
        config.token_limit,
        verbose=verbose,
        quiet=quiet,
        zip_output=zip_output,
        flat_output=config.flat_output,
        single_file=config.single_file,
        frontmatter=frontmatter,
    )
