"""CLI wrapper for Google Search Console export."""

from __future__ import annotations

from pathlib import Path
from typing import Optional

import typer

from worai.core.config_resolver import (
    load_profile_settings,
    resolve_oauth_client_secrets,
    resolve_token_path,
    resolve_value,
)
from worai.core.gsc import GscOptions, run as gsc_run
from worai.core.output import OutputFormat, write_output
from worai.errors import UsageError

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


def _resolve_value(
    ctx: typer.Context,
    value: str | None,
    path: str,
    env_key: str | None,
) -> str | None:
    profile_settings, _ = load_profile_settings(ctx)
    env_keys = [env_key] if env_key else []
    return resolve_value(value, profile_settings, paths=[path], env_keys=env_keys)


@app.callback(invoke_without_command=True)
def run(
    ctx: typer.Context,
    site: str = typer.Option(..., "--site", help="GSC property to query."),
    client_secrets: str | None = typer.Option(None, "--client-secrets", help="OAuth2 client secrets JSON."),
    token: str | None = typer.Option(None, "--token", help="Path to store OAuth2 token."),
    port: int = typer.Option(8080, "--port", help="Local redirect port for OAuth flow."),
    output: Optional[Path] = typer.Option(None, "--output", "-o", help="Output file path."),
    fmt: OutputFormat = typer.Option(OutputFormat.csv, "--format", "-f", help="Output format."),
    row_limit: int = typer.Option(25000, "--row-limit", help="Row limit for GSC API pagination."),
    search_type: str = typer.Option("web", "--type", help="Search type."),
    data_state: str = typer.Option("all", "--data-state", help="Data state to query."),
) -> None:
    profile_settings, _ = load_profile_settings(ctx)
    resolved_client_secrets = resolve_oauth_client_secrets(client_secrets, profile_settings)
    resolved_token = resolve_token_path(token, profile_settings)

    if not resolved_client_secrets:
        raise UsageError("--client-secrets is required (or set profiles.<name>.oauth.client_secrets in config).")

    # For csv format with no explicit output, fall back to profile setting or default filename.
    dest: Path | None = output
    if dest is None and fmt == OutputFormat.csv:
        resolved_output_str = (
            resolve_value(None, profile_settings, paths=["gsc.output"], env_keys=["GSC_OUTPUT"])
            or "gsc_pages.csv"
        )
        dest = Path(resolved_output_str)

    options = GscOptions(
        site=site,
        client_secrets=resolved_client_secrets,
        token=resolved_token,
        port=port,
        row_limit=row_limit,
        search_type=search_type,
        data_state=data_state,
    )
    rows = gsc_run(options)
    write_output(rows, fmt, dest=dest)
