"""Tool: campaign_report — Detailed campaign analytics with outcomes and stale lead warnings.

Provides deeper analytics than show_status, focused on outcome tracking,
conversion rates, stale lead detection, and engagement ROI.
"""

from __future__ import annotations

import json
import logging
import time as _time

from ..db.queries import (
    find_active_campaign,
    get_campaign,
    get_campaign_outcomes,
    get_campaign_stats,
    get_engagement_stats,
    get_setting,
    get_stale_outreaches,
    list_campaigns,
)
from ..formatter import (
    conversion_rate_display,
    health_rating,
    outcome_icon,
    outcome_label,
    progress_bar,
    stars,
)

logger = logging.getLogger(__name__)


async def run_campaign_report(
    campaign_id: str = "",
) -> str:
    """Generate a detailed analytics report for a campaign.

    Args:
        campaign_id: Which campaign to report on. Uses the active campaign if empty.
    """

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

    # ── Resolve campaign ──
    campaign, err = find_active_campaign(campaign_id)
    if not campaign and not campaign_id:
        campaigns = list_campaigns()
        if not campaigns:
            return (
                "No campaigns to report on.\n\n"
                "Create one first: create_campaign(\"your target description\")"
            )
        campaign = campaigns[0]
    elif not campaign:
        return err

    campaign_id = campaign["id"]
    config = {}
    try:
        config = json.loads(campaign.get("config_json", "{}") or "{}")
    except (json.JSONDecodeError, TypeError):
        pass

    # ── Load all data ──
    stats = get_campaign_stats(campaign_id)
    outcomes = get_campaign_outcomes(campaign_id)
    eng_stats = get_engagement_stats(campaign_id)
    stale = get_stale_outreaches(campaign_id, stale_days=14)

    # Calculate days since creation
    created = campaign.get("created_at", 0)
    days = (int(_time.time()) - created) // 86400 if created else 0

    # ── Section 1: Header ──
    mode_str = "\U0001f916 Autopilot" if campaign.get("mode") == "autopilot" else "\U0001f464 Copilot"
    status_str = campaign.get("status", "active").capitalize()

    output = [
        f"\U0001f4ca Campaign Report: **{campaign['name']}** (Day {days})",
        f"   Mode: {mode_str} | Status: {status_str}",
        f"   Target: {config.get('target_description', 'N/A')}",
        "",
    ]

    # ── Section 2: Funnel ──
    total = stats.get("total_prospects", 0)
    invited = stats.get("invited", 0)
    connected = stats.get("connected", 0)
    replied = stats.get("replied", 0)
    hot = stats.get("hot_leads", 0)
    skipped = stats.get("skipped", 0)

    if total > 0:
        output.append("Funnel:")
        output.append(f"\u251c\u2500\u2500 Prospects:  {progress_bar(total, total, 20)} {total}")

        inv_pct = f"  ({invited * 100 // total}%)" if total > 0 else ""
        output.append(f"\u251c\u2500\u2500 Invited:    {progress_bar(invited, total, 20)} {invited}{inv_pct}")

        acc_str = f"  ({stats['acceptance_rate']:.0%} acceptance)" if invited > 0 else ""
        output.append(f"\u251c\u2500\u2500 Connected:  {progress_bar(connected, total, 20)} {connected}{acc_str}")

        reply_str = f"  ({stats['reply_rate']:.0%} reply rate)" if connected > 0 else ""
        output.append(f"\u251c\u2500\u2500 Replied:    {progress_bar(replied, total, 20)} {replied}{reply_str}")

        output.append(f"\u2514\u2500\u2500 Hot leads:  {progress_bar(hot, total, 20)} {hot}")
        output.append("")

    # ── Section 3: Outcomes ──
    closed_happy = outcomes.get("closed_happy", 0)
    closed_unhappy = outcomes.get("closed_unhappy", 0)
    opted_out = outcomes.get("opted_out", 0)
    total_closed = outcomes.get("total_closed", 0)

    # Count active leads
    active_hot = hot
    active_replied = stats.get("replied", 0) - closed_happy - closed_unhappy
    if active_replied < 0:
        active_replied = 0

    output.append("Outcomes:")
    output.append(f"\u251c\u2500\u2500 \U0001f3c6 Won: {closed_happy}")
    output.append(f"\u251c\u2500\u2500 \U0001f4c9 Lost: {closed_unhappy}")
    if opted_out > 0:
        output.append(f"\u251c\u2500\u2500 \U0001f6ab Opted out: {opted_out}")
    output.append(f"\u251c\u2500\u2500 Conversion: {conversion_rate_display(closed_happy, closed_unhappy)}")

    active_parts = []
    if active_hot > 0:
        active_parts.append(f"{active_hot} hot")
    if active_replied > 0:
        active_parts.append(f"{active_replied} replied")
    active_str = ", ".join(active_parts) if active_parts else "none"
    output.append(f"\u2514\u2500\u2500 Active leads: {active_str}")
    output.append("")

    # ── Section 4: Won deals detail ──
    won_deals = [o for o in outcomes.get("outcomes", []) if o["status"] == "closed_happy"]
    if won_deals:
        output.append("Won deals:")
        for i, deal in enumerate(won_deals):
            is_last = i == len(won_deals) - 1
            prefix = "\u2514\u2500\u2500" if is_last else "\u251c\u2500\u2500"
            role = deal.get("title", "")
            if deal.get("company"):
                role += f" at {deal['company']}" if role else deal["company"]
            reason_str = f" ({deal['reason']})" if deal.get("reason") else ""
            output.append(f"{prefix} {deal['name']} \u2014 {role}{reason_str}")
        output.append("")

    # ── Section 5: Lost deals detail (if any) ──
    lost_deals = [o for o in outcomes.get("outcomes", []) if o["status"] == "closed_unhappy"]
    if lost_deals:
        output.append("Lost deals:")
        for i, deal in enumerate(lost_deals):
            is_last = i == len(lost_deals) - 1
            prefix = "\u2514\u2500\u2500" if is_last else "\u251c\u2500\u2500"
            role = deal.get("title", "")
            if deal.get("company"):
                role += f" at {deal['company']}" if role else deal["company"]
            reason_str = f" ({deal['reason']})" if deal.get("reason") else ""
            output.append(f"{prefix} {deal['name']} \u2014 {role}{reason_str}")
        output.append("")

    # ── Section 6: Stale leads warning ──
    if stale:
        output.append(f"\u26a0\ufe0f Stale leads (no activity 14+ days):")
        for i, s in enumerate(stale[:5]):
            is_last = i == min(4, len(stale) - 1)
            prefix = "\u2514\u2500\u2500" if is_last else "\u251c\u2500\u2500"
            role = s.get("title", "")
            if s.get("company"):
                role += f" at {s['company']}" if role else s["company"]
            output.append(f"{prefix} {s['name']} \u2014 {role} (last activity: {s['days_stale']}d ago)")
        if len(stale) > 5:
            output.append(f"    ... and {len(stale) - 5} more")
        output.append(f"   \u2192 Use close_outreach() to resolve or send_followup() to re-engage")
        output.append("")

    # ── Section 7: Engagement metrics ──
    comments = eng_stats.get("comments", 0)
    reactions = eng_stats.get("reactions", 0)
    eng_total = comments + reactions
    if eng_total > 0:
        output.append("Engagement:")
        output.append(f"\u251c\u2500\u2500 Comments: {comments}")
        output.append(f"\u251c\u2500\u2500 Reactions: {reactions}")
        output.append(f"\u2514\u2500\u2500 Total touches: {eng_total}")
        output.append("")

    # ── Section 8: Account health ──
    acc_rate = stats.get("acceptance_rate", 0)
    if invited > 0:
        output.append(f"Account Health: {health_rating(acc_rate)}")
        mature = stats.get("mature_acceptance_rate", 0)
        if mature > 0 and mature != acc_rate:
            output.append(f"   (7-day mature rate: {mature:.0%})")
        output.append("")

    # ── Section 9: Remaining queue ──
    pending = total - invited - skipped
    if pending > 0:
        output.append(f"\U0001f4e6 {pending} prospects still queued for outreach.")

    return "\n".join(output)
