"""Contrat hub → micro-script Python.

Le hub lance `python -m <module>` en transmettant les arguments tels quels et
en héritant du terminal. Chaque micro-script accepte donc les mêmes options de
base et prompte lui-même pour ce qui manque.
"""

from __future__ import annotations

import argparse
from pathlib import Path

import questionary

from csvkit_py import workspace


def base_parser(description: str) -> argparse.ArgumentParser:
    """Parser partagé : `--input` / `--out-dir`, tous deux optionnels."""
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument("-i", "--input", type=Path, help="CSV source (sinon : menu)")
    parser.add_argument("-o", "--out-dir", type=Path, help="dossier de sortie")
    return parser


def resolve_input(root: Path, given: Path | None) -> Path:
    """Renvoie le CSV à traiter : celui passé en argument, sinon un choix.

    Le mode non-interactif (`--input`) doit rester utilisable en script : on ne
    prompte jamais quand le chemin est fourni, on échoue.
    """
    if given is not None:
        path = given if given.is_absolute() else root / given
        if not path.is_file():
            raise SystemExit(f"Erreur : {path} n'est pas un fichier")
        return path

    candidates = workspace.find_csv(root)
    if not candidates:
        raise SystemExit(
            f"Erreur : aucun CSV dans {workspace.sources_dir(root)} — dépose un fichier "
            "ou passe --input"
        )

    picked = questionary.select(
        "Fichier CSV source :",
        choices=[str(p.relative_to(root)) for p in candidates],
    ).ask()

    if picked is None:  # Ctrl-C
        raise SystemExit(130)
    return root / picked


def rel(path: Path, root: Path) -> str:
    """Chemin relatif à la racine si possible, absolu sinon."""
    try:
        return str(path.relative_to(root))
    except ValueError:
        return str(path)
