"""
Formatting and display utilities for AKShare CLI harness.
"""

import sys
from typing import Optional

import pandas as pd

from akshare_cli.core.export import format_csv, format_json, format_table


def display_result(
    df: pd.DataFrame,
    output_format: str = "table",
    max_rows: Optional[int] = None,
    show_index: bool = False,
    output_file: Optional[str] = None,
) -> str:
    """
    Format and display a DataFrame result.

    Args:
        df: The DataFrame to display.
        output_format: One of "table", "json", "csv".
        max_rows: Maximum rows to display.
        show_index: Whether to show row index.
        output_file: If set, write output to this file path.

    Returns:
        The formatted string.
    """
    if output_format == "json":
        output = format_json(df, max_rows=max_rows)
    elif output_format == "csv":
        output = format_csv(df, max_rows=max_rows)
    else:
        output = format_table(df, max_rows=max_rows, show_index=show_index)

    if output_file:
        from akshare_cli.core.export import auto_export
        auto_export(df, output_file)
        return f"Saved to {output_file}"

    return output


def print_error(message: str) -> None:
    """Print an error message to stderr."""
    print(f"Error: {message}", file=sys.stderr)


def print_info(message: str) -> None:
    """Print an informational message."""
    print(message)


def truncate_string(s: str, max_len: int = 60) -> str:
    """Truncate a string with ellipsis if it exceeds max_len."""
    if len(s) <= max_len:
        return s
    return s[: max_len - 3] + "..."
