"""CLI commands for canonical URL workflows."""

from __future__ import annotations

from pathlib import Path

import typer

from worai.core.config_resolver import (
    load_profile_settings,
    resolve_gsc_site_id,
    resolve_oauth_client_secrets,
    resolve_token_path,
    resolve_value,
)
from worai.core.canonicals import CanonicalsDedupeOptions, run_dedupe
from worai.core.output_template import render_output_path_template
from worai.errors import UsageError

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


@app.command("dedupe")
def dedupe(
    ctx: typer.Context,
    input_csv: str = typer.Option(..., "--input", help="Input CSV with required columns: url,title."),
    output_csv: str | None = typer.Option(None, "--output", help="Output CSV path."),
    site_url: str | None = typer.Option(None, "--site", help="GSC property URL (e.g., sc-domain:example.com)."),
    interval: str | None = typer.Option(None, "--interval", help="GSC interval, e.g. 28d, 4w, 1m."),
    url_regex: str | None = typer.Option(None, "--url-regex", help="Optional regex to filter input URLs."),
    concurrency: str | None = typer.Option(None, "--concurrency", help="Max concurrent requests or 'auto'."),
    request_timeout_sec: float | None = typer.Option(None, "--request-timeout-sec", help="Per-request timeout in seconds."),
    service_account: str | None = typer.Option(
        None,
        "--service-account",
        "--service-account-file",
        help="Google service account as file path or JSON body (--service-account-file is deprecated alias).",
    ),
    client_secrets: str | None = typer.Option(
        None,
        "--client-secrets",
        help="OAuth2 client secrets JSON path (required to create/repair user token).",
    ),
    token: str | None = typer.Option(None, "--token", help="OAuth token JSON path."),
    port: int = typer.Option(8080, "--port", help="OAuth local redirect port."),
) -> None:
    """Dedupe canonicals by title cluster using GSC impressions from the SDK."""
    profile_settings, profile_name = load_profile_settings(ctx)

    resolved_site = resolve_gsc_site_id(site_url, profile_settings)
    if not resolved_site:
        raise UsageError("--site is required (or set profiles.<name>.gsc_site_id / GSC_ID).")

    resolved_service_account = resolve_value(
        service_account,
        profile_settings,
        paths=["oauth.service_account", "sheets_service_account"],
        env_keys=["OAUTH_SERVICE_ACCOUNT", "SHEETS_SERVICE_ACCOUNT"],
    )
    if not service_account and "sheets_service_account" in profile_settings and not resolve_value(
        None, profile_settings, paths=["oauth.service_account"]
    ):
        typer.secho(
            "Deprecation: profiles.<name>.sheets_service_account is deprecated; "
            "use profiles.<name>.oauth.service_account.",
            err=True,
            fg=typer.colors.YELLOW,
        )

    resolved_client_secrets = resolve_oauth_client_secrets(client_secrets, profile_settings)
    if resolved_service_account and resolved_client_secrets:
        raise UsageError("Use either --service-account or --client-secrets/--token, not both.")

    resolved_token = resolve_token_path(token, profile_settings)
    resolved_interval = str(
        resolve_value(
            interval,
            profile_settings,
            paths=["canonicals.interval"],
        )
        or "28d"
    )
    resolved_concurrency = str(
        resolve_value(
            concurrency,
            profile_settings,
            paths=["canonicals.concurrency"],
        )
        or "auto"
    )
    resolved_timeout_raw = resolve_value(
        request_timeout_sec,
        profile_settings,
        paths=["canonicals.request_timeout_sec"],
    )
    resolved_timeout = float(resolved_timeout_raw or 30.0)

    output_template = str(
        resolve_value(
            output_csv,
            profile_settings,
            paths=["canonicals.output"],
        )
        or "canonical_{profile}_{date}_{seq:3}.csv"
    )
    resolved_output = str(
        render_output_path_template(
            output_template,
            profile_name=profile_name,
        )
    )

    options = CanonicalsDedupeOptions(
        input_csv=input_csv,
        output_csv=resolved_output,
        site_url=resolved_site,
        interval=resolved_interval,
        url_regex=url_regex,
        concurrency=resolved_concurrency,
        request_timeout_sec=resolved_timeout,
        service_account=resolved_service_account,
        client_secrets=resolved_client_secrets,
        token=resolved_token,
        oauth_port=port,
    )
    result = run_dedupe(options)
    typer.echo(f"Wrote {len(result)} rows to {Path(resolved_output)}")
