"""Tool: retry_failed — Reset error outreaches to pending for retry.

Finds outreaches stuck in 'error' status and resets them so they
can be picked up by generate_and_send() again.
"""

from __future__ import annotations

import logging

from ..db.queries import (
    get_campaign,
    get_error_outreaches,
    get_setting,
    log_action,
    update_outreach,
)

logger = logging.getLogger(__name__)


async def run_retry_failed(campaign_id: str = "") -> str:
    """Reset error outreaches to pending for retry."""

    setup_done = get_setting("setup_complete", False)
    if not setup_done:
        return (
            "Setup required before retrying.\n\n"
            "Please run setup_profile first."
        )

    # Validate campaign if specified
    if campaign_id:
        campaign = get_campaign(campaign_id)
        if not campaign:
            return f"Campaign not found: {campaign_id}"

    # Find error outreaches
    errors = get_error_outreaches(campaign_id)

    if not errors:
        scope = f"in campaign '{campaign['name']}'" if campaign_id else "across all campaigns"
        return (
            f"No failed outreaches {scope}.\n\n"
            "All outreaches are in healthy states.\n"
            "Use show_status() to see your dashboard."
        )

    # Reset each error outreach to pending
    reset_count = 0
    names: list[str] = []
    for err in errors:
        oid = err["outreach_id"]
        update_outreach(oid, status="pending", next_action=None)
        log_action(
            "outreach_retried",
            outreach_id=oid,
            result="reset",
            details={
                "prospect": err.get("name", "Unknown"),
                "campaign_id": err.get("campaign_id", ""),
            },
        )
        reset_count += 1
        names.append(err.get("name", "Unknown"))

    logger.info(f"Retried {reset_count} failed outreaches")

    # Format output
    names_preview = ", ".join(names[:5])
    if len(names) > 5:
        names_preview += f", ... and {len(names) - 5} more"

    return (
        f"Reset {reset_count} failed outreach{'es' if reset_count != 1 else ''} to pending.\n\n"
        f"Prospects: {names_preview}\n\n"
        "These prospects are back in the queue.\n"
        "Use generate_and_send() to process them."
    )
