"""Tool: skip_prospect — Remove a prospect from the outreach queue.

Marks a prospect as 'skipped' so they won't receive any more
invitations, follow-ups, or engagements. Useful for bad-fit
prospects found during copilot review.
"""

from __future__ import annotations

import logging

from ..db.queries import (
    find_active_campaign,
    get_outreach,
    get_setting,
    log_action,
    update_outreach,
)
from ..db.schema import get_db

logger = logging.getLogger(__name__)


async def run_skip_prospect(
    outreach_id: str = "",
    campaign_id: str = "",
) -> str:
    """Skip a prospect, removing them from the outreach queue.

    If outreach_id is provided, skips that specific outreach.
    Otherwise, finds the next pending prospect in the campaign.
    """

    # ── Pre-checks ──
    setup_done = get_setting("setup_complete", False)
    if not setup_done:
        return (
            "Setup required before skipping prospects.\n\n"
            "Please run setup_profile first."
        )

    # ── Resolve outreach ──
    if outreach_id:
        outreach = get_outreach(outreach_id)
        if not outreach:
            return f"Outreach not found: {outreach_id}"
        if outreach["status"] == "skipped":
            return "This prospect is already skipped."
    else:
        # Find next pending prospect in campaign
        campaign, err = find_active_campaign(campaign_id)
        if not campaign:
            return err
        campaign_id = campaign["id"]

        # Find next pending outreach
        db = get_db()
        row = db.execute(
            """SELECT o.id as outreach_id, o.status, o.campaign_id, o.contact_id
               FROM outreaches o
               JOIN contacts c ON o.contact_id = c.id
               WHERE o.campaign_id = ?
                 AND o.status = 'pending'
               ORDER BY c.fit_score ASC
               LIMIT 1""",
            (campaign_id,),
        ).fetchone()
        db.close()

        if not row:
            return (
                f"No pending prospects to skip in '{campaign.get('name', 'campaign')}'.\n\n"
                "All prospects have already been invited or skipped."
            )
        outreach_id = row["outreach_id"]
        outreach = get_outreach(outreach_id)
        if not outreach:
            return "Outreach not found."

    # ── Get contact info for display ──
    db = get_db()
    contact = db.execute(
        """SELECT name, title, company, fit_score
           FROM contacts WHERE id = ?""",
        (outreach["contact_id"],),
    ).fetchone()
    db.close()

    contact_name = "Unknown"
    role_str = ""
    if contact:
        c = dict(contact)
        contact_name = c.get("name", "Unknown")
        role_str = c.get("title", "")
        if c.get("company"):
            role_str += f" at {c['company']}" if role_str else c["company"]

    # ── Skip the prospect ──
    old_status = outreach["status"]
    update_outreach(outreach_id, status="skipped", next_action=None)
    log_action(
        "prospect_skipped",
        outreach_id=outreach_id,
        result="skipped",
        details={"prospect": contact_name, "previous_status": old_status},
    )

    output = [
        f"Skipped **{contact_name}**" + (f" ({role_str})" if role_str else ""),
        f"   Previous status: {old_status}",
        "",
    ]

    # ── Show next pending prospect as hint ──
    cid = outreach.get("campaign_id", campaign_id)
    if cid:
        db = get_db()
        next_row = db.execute(
            """SELECT c.name, c.title, c.company, c.fit_score
               FROM outreaches o
               JOIN contacts c ON o.contact_id = c.id
               WHERE o.campaign_id = ?
                 AND o.status = 'pending'
               ORDER BY c.fit_score DESC
               LIMIT 1""",
            (cid,),
        ).fetchone()
        pending_count = db.execute(
            "SELECT COUNT(*) as c FROM outreaches WHERE campaign_id = ? AND status = 'pending'",
            (cid,),
        ).fetchone()["c"]
        db.close()

        if next_row:
            n = dict(next_row)
            next_name = n.get("name", "Unknown")
            next_role = n.get("title", "")
            if n.get("company"):
                next_role += f" at {n['company']}" if next_role else n["company"]
            output.append(f"Next up: {next_name} ({next_role})")
            output.append(f"{pending_count} prospect{'s' if pending_count != 1 else ''} remaining in queue.")
        else:
            output.append("No more pending prospects in this campaign.")

    return "\n".join(output)
