"""CLI wrapper for dil_import."""

from __future__ import annotations

from pathlib import Path

import typer
import pandas as pd

from worai.core.dil_import import DilImportOptions, run as import_run
from worai.errors import UsageError

app = typer.Typer(
    add_completion=False, no_args_is_help=True, invoke_without_command=True
)

REQUIRED_COLUMNS = {"source_url", "target_url", "target_anchor_text", "target_position"}


def verify_csv(file_path: str):
    path = Path(file_path)

    if not path.exists():
        raise typer.BadParameter(f"File not found: {file_path}")

    if path.suffix.lower() != ".csv":
        raise typer.BadParameter("The file must be a CSV.")

    try:
        df_header = pd.read_csv(file_path, nrows=0)
        actual_columns = set(df_header.columns)

        missing = REQUIRED_COLUMNS - actual_columns
        if missing:
            raise typer.BadParameter(f"Missing columns: {', '.join(missing)}")

    except Exception as e:
        raise typer.BadParameter(f"Could not read CSV header: {e}")

    return file_path

@app.callback(invoke_without_command=True)
def run(
    ctx: typer.Context,
    api_key: str = typer.Argument(..., help="WordLift API key."),
    csv_file: str = typer.Argument(
        ...,
        help="CSV file with: source_url, target_url, target_anchor_text, target_position.",
        callback=verify_csv  # This triggers the validation logic
    ),
) -> None:
    if not api_key:
        raise UsageError("WordLift key is required.")

    options = DilImportOptions(api_key=api_key, csv_file=csv_file)
    import_run(options)
