"""Format ihyee API responses as readable text for LLM consumption."""
from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ihyee.models import ContentItem, FetchResponse, SearchResponse


def format_search_results(response: "SearchResponse") -> str:
    """Format a SearchResponse into readable text.

    Produces a numbered list of results with title, URL, summary,
    and key metadata.  Designed to be consumed by an LLM agent.
    """
    if not response.content:
        return f"No results found for query: {response.query}"

    parts: list = [
        f"Found {response.results_count} results for: {response.query}",
        "",
    ]

    for i, item in enumerate(response.content, 1):
        parts.append(_format_content_item(item, index=i))

    return "\n".join(parts)


def format_fetch_results(response: "FetchResponse") -> str:
    """Format a FetchResponse into readable text."""
    if not response.content:
        return "No content extracted from the provided URLs."

    parts: list = []
    for i, item in enumerate(response.content, 1):
        parts.append(_format_content_item(item, index=i))

    return "\n".join(parts)


def _format_content_item(item: "ContentItem", *, index: int) -> str:
    """Format a single ContentItem into a readable block."""
    lines: list = []

    url = item.url or "(no URL)"
    lines.append(f"--- Result {index} ---")
    lines.append(f"URL: {url}")

    if item.text:
        text = item.text

        if text.error:
            lines.append(f"Error: {text.error}")
        else:
            if text.author and text.author != "Unknown":
                lines.append(f"Author: {text.author}")
            if text.date_published and text.date_published != "Unknown":
                lines.append(f"Published: {text.date_published}")

            if text.summary:
                lines.append(f"Summary: {text.summary}")

            if text.full_text:
                full = text.full_text
                if len(full) > 4000:
                    full = full[:4000] + "... [truncated]"
                lines.append(f"Content: {full}")

            if text.links:
                link_strs = [
                    f"  - {link.text}: {link.url}" for link in text.links[:10]
                ]
                if len(text.links) > 10:
                    link_strs.append(f"  ... and {len(text.links) - 10} more links")
                lines.append("Links:")
                lines.extend(link_strs)

    lines.append("")
    return "\n".join(lines)
