from __future__ import annotations
import argparse
import sys
from pathlib import Path
from .pipeline import run, find_pdfs


def _duplicate_stems(paths: list[Path]) -> dict[str, list[Path]]:
    groups: dict[str, list[Path]] = {}
    for p in paths:
        groups.setdefault(p.stem.casefold(), []).append(p)
    return {k: v for k, v in groups.items() if len(v) > 1}


def _ensure_unique_output_names(paths: list[Path]) -> None:
    dups = _duplicate_stems(paths)
    if not dups:
        return

    lines = [
        "[error] Multiple input PDFs would map to the same output name.",
        "        Filenames without extension must be unique.",
        "",
    ]
    for stem, items in sorted(dups.items()):
        lines.append(f"        {stem}:")
        for p in items:
            lines.append(f"          - {p}")
    raise SystemExit("\n".join(lines))


def main() -> None:
    ap = argparse.ArgumentParser(
        description=(
            "PDF Image Quality Checker (pdfimgq)\n"
            "Extract images from PDF documents and report technical quality metrics.\n\n"
            "GUI MODE:\n"
            "  To launch the interactive desktop application, use:\n"
            "  pdfimgq --gui"
        ),
        formatter_class=argparse.RawTextHelpFormatter
    )

    ap.add_argument("--gui", action="store_true",
                    help="Launch the Graphical User Interface (GUI) and ignore other arguments.")

    ap.add_argument("--input", type=Path, default=Path("inputs"),
                    help="Input PDF file or directory (default: inputs/)")
    ap.add_argument("--outdir", type=Path, default=Path("outputs"),
                    help="Output directory for extracted images & reports (default: outputs/)")
    ap.add_argument("--recursive", action="store_true",
                    help="If --input is a directory, search PDFs recursively.")

    if len(sys.argv) == 1:
        ap.print_help()
        return

    args = ap.parse_args()

    if args.gui:
        from .gui.app import main as gui_main
        gui_main()
        sys.exit(0)

    in_path: Path = args.input
    out_dir: Path = args.outdir

    if in_path.is_dir():
        pdfs = list(find_pdfs(in_path, recursive=args.recursive))
        if not pdfs:
            print(f"[info] No PDFs found in {in_path} (use --recursive to search subfolders).")
            return
        print(f"[info] Found {len(pdfs)} PDF(s) in {in_path}.")
    else:
        if not in_path.exists():
            raise SystemExit(f"[error] Input not found: {in_path}")
        pdfs = [in_path]

    _ensure_unique_output_names(pdfs)

    for i, pdf in enumerate(pdfs, 1):
        try:
            pdf_name = pdf.relative_to(in_path) if in_path.is_dir() else pdf.name
        except Exception:
            pdf_name = pdf.name

        print(f"\n\nPDF {i}/{len(pdfs)}: {pdf_name}")
        base = pdf.stem
        per_pdf_out = out_dir / base
        per_pdf_csv = out_dir / f"{base}.csv"
        run(pdf.resolve(), per_pdf_out.resolve(), per_pdf_csv.resolve())

    print(f"\nDone. Processed {len(pdfs)} PDF file(s).")
    print(f"Reports written to: {out_dir.resolve()}")
