"""CLI wrapper for entity-matrix."""

from __future__ import annotations

from pathlib import Path
from typing import Optional

import typer

from worai.core.config_resolver import (
    resolve_gsheets_credentials,
    resolve_gsheets_sheet_name,
    resolve_gsheets_spreadsheet_id,
)
from worai.core.profile_loader import load_raw_profile
from worai.core.entity_matrix import EntityMatrixOptions, build_entity_matrix
from worai.core.output import OutputFormat, write_output
from worai.errors import UsageError


def _to_presence(rows: list[dict]) -> list[dict]:
    """Replace integer counts with ✅ (present) or '' (absent/zero)."""
    return [
        {k: ("✅" if v else "") if k != "url" else v for k, v in row.items()}
        for row in rows
    ]


def run(
    ctx: typer.Context,
    filename: str = typer.Argument(..., help="Path to Turtle (.ttl) graph file."),
    exclude_type: Optional[list[str]] = typer.Option(
        None,
        "--exclude-type",
        "-x",
        help="Entity type short name to exclude (e.g. WebPage). Repeat to exclude multiple.",
    ),
    cluster: bool = typer.Option(
        False,
        "--cluster/--no-cluster",
        help=(
            "Aggregate URL rows that share a common parent path and identical "
            "entity-type set into a single wildcard row (e.g. /blog/*)."
        ),
    ),
    depth: int = typer.Option(
        1,
        "--depth",
        help="Subgraph relationship hops for referenced entity traversal.",
        show_default=True,
    ),
    count: bool = typer.Option(
        False,
        "--count/--no-count",
        help="Show integer counts instead of ✅ presence markers.",
    ),
    fmt: OutputFormat = typer.Option(OutputFormat.table, "--format", "-f", help="Output format."),
    output: Optional[Path] = typer.Option(None, "--output", "-o", help="Output file path."),
    gsheets_credentials: Optional[str] = typer.Option(
        None,
        "--gsheets-credentials",
        help="Service-account JSON path (required for gsheets format).",
        show_default=False,
    ),
    gsheets_id: Optional[str] = typer.Option(
        None,
        "--gsheets-id",
        help="Google Sheets spreadsheet ID (required for gsheets format).",
        show_default=False,
    ),
    gsheets_sheet: Optional[str] = typer.Option(
        None,
        "--gsheets-sheet",
        help="Worksheet tab name (required for gsheets format).",
        show_default=False,
    ),
) -> None:
    try:
        options = EntityMatrixOptions(
            filename=filename,
            exclude_types=list(exclude_type) if exclude_type else [],
            cluster=cluster,
            subgraph_depth=depth,
        )
        rows = build_entity_matrix(options)
        if not count:
            rows = _to_presence(rows)
    except FileNotFoundError:
        raise UsageError(f"File not found: '{filename}'")
    except Exception as exc:
        raise UsageError(f"Failed to build entity matrix: {exc}") from exc

    fmt_options: dict = {}
    if fmt == OutputFormat.gsheets:
        raw = load_raw_profile(ctx)
        creds = resolve_gsheets_credentials(gsheets_credentials, raw)
        shid = resolve_gsheets_spreadsheet_id(gsheets_id, raw)
        sheet = resolve_gsheets_sheet_name(gsheets_sheet, raw)
        if creds:
            fmt_options["credentials_file"] = creds
        if shid:
            fmt_options["spreadsheet_id"] = shid
        if sheet:
            fmt_options["sheet_name"] = sheet

    write_output(rows, fmt, dest=output, **fmt_options)
