import sys
from typing import Iterable

from .core import count_words


def render_table(rows: Iterable[tuple[str, int | str]]) -> str:
    """Render a simple table for CLI output."""
    col1_header = "File"
    col2_header = "Word Count"

    rows_list = list(rows)
    if not rows_list:
        return "No files processed."

    col1_width = max(len(col1_header), max(len(r[0]) for r in rows_list))
    col2_width = max(len(col2_header), max(len(str(r[1])) for r in rows_list))

    divider = f"+{'-' * (col1_width + 2)}+{'-' * (col2_width + 2)}+"
    lines = [divider, f"| {col1_header:<{col1_width}} | {col2_header:<{col2_width}} |", divider]

    for filename, count in rows_list:
        count_str = f"{count:,}" if isinstance(count, int) else str(count)
        lines.append(f"| {filename:<{col1_width}} | {count_str:<{col2_width}} |")

    lines.append(divider)
    return "\n".join(lines)


def main(argv=None) -> int:
    if argv is None:
        argv = sys.argv[1:]

    if not argv:
        print("Usage: countpdfwords <file1.pdf> [file2.pdf] [...]")
        return 1

    results = []
    for path in argv:
        try:
            count = count_words(path)
            results.append((path, count))
        except FileNotFoundError:
            results.append((path, "Error: file not found"))
        except Exception as exc:
            results.append((path, f"Error: {exc}"))

    print(render_table(results))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
