"""Output formatting for SeevoMap CLI."""

import json
import sys


def print_search_results(results: list[dict]):
    """Pretty-print search results to terminal."""
    if not results:
        print("No results found.")
        return
    for i, r in enumerate(results, 1):
        raw = r.get("raw", "")
        if raw:
            print(f"[{i}] {raw}")
            print()


def print_inject(text: str):
    """Print inject text (designed for piping to file)."""
    sys.stdout.write(text)
    if not text.endswith("\n"):
        sys.stdout.write("\n")


def print_node(node: dict):
    """Pretty-print a node."""
    print(json.dumps(node, indent=2, ensure_ascii=False))


def print_stats(stats: dict):
    """Print graph statistics."""
    print(json.dumps(stats, indent=2, ensure_ascii=False))


def print_submit_result(result: dict):
    """Print submit result."""
    status = result.get("status", "unknown")
    if status == "ok":
        print(f"Submitted successfully. Node ID: {result.get('id', '?')}")
    elif status == "error":
        errors = result.get("errors", [result.get("message", "Unknown error")])
        print(f"Error: {', '.join(errors) if isinstance(errors, list) else errors}")
    elif status == "warning":
        print(f"Warning: {result.get('message', '')}")
        print(f"Node ID: {result.get('id', '?')}")
    else:
        print(json.dumps(result, indent=2))


def print_review_result(result: dict):
    """Print review result."""
    status = result.get("status", "unknown")
    if status == "ok":
        print(f"Node {result.get('id', '?')} → {result.get('new_status', '?')}")
    else:
        print(f"Error: {result.get('message', json.dumps(result))}")


def print_pending(nodes: list[dict]):
    """Print pending review nodes."""
    if not nodes:
        print("No pending nodes.")
        return
    print(f"Pending review: {len(nodes)} nodes\n")
    for n in nodes:
        print(f"  [{n.get('id', '?')}] {n.get('domain', '')} | {n.get('idea', '')[:80]}")
        if n.get("submitted_at"):
            print(f"           submitted: {n['submitted_at']}")
        print()
