"""Tool 5: show_status — Dashboard in the chat.

Shows campaign stats, acceptance rate, reply rate, hot leads,
account health, and free tier usage.

The chat IS the dashboard. Forever.
"""

from __future__ import annotations

import json
import logging
from typing import Any

from ..config import get_tier
from ..constants import (
    FREE_MAX_CAMPAIGNS,
    FREE_MONTHLY_INVITATIONS,
    FREE_MONTHLY_MESSAGES,
    TIER_PRO,
)
from ..db.queries import (
    get_campaign,
    get_campaign_stats,
    get_monthly_usage,
    get_rate_limit_today,
    get_setting,
    list_campaigns,
)
from ..db.schema import get_db
from ..formatter import health_rating, progress_bar, stars

logger = logging.getLogger(__name__)


async def run_show_status(campaign_id: str = "") -> str:
    """Show outreach dashboard.

    If campaign_id is provided: show detailed stats for that campaign.
    If empty: show overview of all campaigns + account health.
    """

    setup_done = get_setting("setup_complete", False)
    if not setup_done:
        return (
            "👋 Welcome to HeyLead!\n\n"
            "You haven't set up your profile yet. Start with:\n"
            "  → setup_profile (connect your LinkedIn + AI)\n\n"
            "Then:\n"
            "  → create_campaign (\"find me fintech CTOs\")\n"
            "  → generate_and_send (personalized messages)\n"
            "  → check_replies (see who responded)\n"
            "  → show_status (this dashboard)"
        )

    # ── Specific campaign view ──
    if campaign_id:
        return await _show_campaign_detail(campaign_id)

    # ── Overview ──
    return await _show_overview()


async def _show_overview() -> str:
    """Show overview of all campaigns + account health."""

    campaigns = list_campaigns()
    tier = get_tier()
    rate_data = get_rate_limit_today()
    usage = get_monthly_usage()

    output = ["📊 **HeyLead Dashboard**\n"]

    # ── Account Health ──
    sent = rate_data.get("sent", 0)
    accepted = rate_data.get("accepted", 0)
    daily_limit = rate_data.get("daily_limit", 15)
    acceptance_rate = accepted / sent if sent > 0 else 0.0

    output.append("Account Health:")
    output.append(f"├── Rating: {health_rating(acceptance_rate)}")
    output.append(f"├── Today: {sent}/{daily_limit} invitations sent")
    output.append(f"├── Acceptance rate: {acceptance_rate:.0%}" if sent > 0 else "├── Acceptance rate: No data yet")
    output.append(f"└── Daily limit: {daily_limit}/day (adaptive)")
    output.append("")

    # ── Free tier usage ──
    if tier != TIER_PRO:
        inv_used = usage.get("invitations_sent", 0)
        msg_used = usage.get("messages_sent", 0)

        output.append("Free Tier Usage (this month):")
        output.append(f"├── Invitations: {inv_used}/{FREE_MONTHLY_INVITATIONS} {progress_bar(inv_used, FREE_MONTHLY_INVITATIONS, 15)}")
        output.append(f"├── Messages: {msg_used}/{FREE_MONTHLY_MESSAGES} {progress_bar(msg_used, FREE_MONTHLY_MESSAGES, 15)}")
        output.append(f"└── Campaigns: {len([c for c in campaigns if c['status'] in ('active', 'draft')])}/{FREE_MAX_CAMPAIGNS}")
        output.append("")

    # ── Campaigns ──
    if not campaigns:
        output.append("No campaigns yet.")
        output.append("Create one: create_campaign(\"your target description\")")
    else:
        output.append(f"Campaigns ({len(campaigns)}):")
        for i, camp in enumerate(campaigns):
            is_last = i == len(campaigns) - 1
            prefix = "└──" if is_last else "├──"

            stats = get_campaign_stats(camp["id"])
            status_icon = {
                "active": "🟢",
                "paused": "⏸️",
                "completed": "✅",
                "draft": "📝",
            }.get(camp["status"], "⚪")

            hot = stats.get("hot_leads", 0)
            hot_str = f" 🔥{hot}" if hot > 0 else ""

            output.append(
                f"{prefix} {status_icon} {camp['name']} — "
                f"{stats['invited']} sent, "
                f"{stats['connected']} connected, "
                f"{stats['replied']} replied{hot_str}"
            )

    output.append("")

    # ── Hot leads summary ──
    db = get_db()
    hot_leads = db.execute(
        """SELECT c.name, c.title, c.company, c.linkedin_url
           FROM outreaches o
           JOIN contacts c ON o.contact_id = c.id
           WHERE o.status = 'hot_lead'
           ORDER BY o.updated_at DESC
           LIMIT 5"""
    ).fetchall()
    db.close()

    if hot_leads:
        output.append(f"🔥 Hot Leads ({len(hot_leads)}):")
        for i, lead in enumerate(hot_leads):
            l = dict(lead)
            is_last = i == len(hot_leads) - 1
            prefix = "└──" if is_last else "├──"
            role = l.get("title", "")
            if l.get("company"):
                role += f" at {l['company']}" if role else l["company"]
            output.append(f"{prefix} {l['name']} — {role}")
        output.append("")

    # ── Quick actions ──
    output.append("Quick actions:")
    output.append("├── \"send messages\" → generate_and_send")
    output.append("├── \"any replies?\" → check_replies")
    output.append("└── \"create campaign\" → create_campaign")

    return "\n".join(output)


async def _show_campaign_detail(campaign_id: str) -> str:
    """Show detailed stats for a specific campaign."""

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

    stats = get_campaign_stats(campaign_id)
    config = json.loads(campaign.get("config_json", "{}"))
    icp = json.loads(campaign.get("icp_json", "{}"))

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

    output = [
        f"📊 Campaign: **{campaign['name']}** (Day {days})",
        f"   Mode: {'🤖 Autopilot' if campaign.get('mode') == 'autopilot' else '👤 Copilot'}",
        f"   Target: {config.get('target_description', 'N/A')}",
        "",
    ]

    # Stats tree
    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)
    pending = total - invited

    output.append("Progress:")
    output.append(f"├── Invitations sent: {invited}")
    output.append(f"├── Accepted: {connected} ({stats['acceptance_rate']:.0%})" if invited > 0 else f"├── Accepted: {connected}")
    output.append(f"├── Replies: {replied} ({stats['reply_rate']:.0%})" if connected > 0 else f"├── Replies: {replied}")
    output.append(f"├── Hot leads: {hot} 🔥" if hot > 0 else f"├── Hot leads: {hot}")
    output.append(f"└── Remaining: {pending} prospects queued")
    output.append("")

    # Funnel visualization
    if invited > 0:
        output.append("Funnel:")
        output.append(f"├── Queued:    {progress_bar(total, total, 20)} {total}")
        output.append(f"├── Sent:      {progress_bar(invited, total, 20)} {invited}")
        output.append(f"├── Connected: {progress_bar(connected, total, 20)} {connected}")
        output.append(f"├── Replied:   {progress_bar(replied, total, 20)} {replied}")
        output.append(f"└── Hot leads: {progress_bar(hot, total, 20)} {hot}")
        output.append("")

    # Top prospects with status
    db = get_db()
    top_contacts = db.execute(
        """SELECT c.name, c.title, c.company, c.fit_score, o.status
           FROM contacts c
           JOIN outreaches o ON o.contact_id = c.id
           WHERE c.campaign_id = ?
           ORDER BY c.fit_score DESC
           LIMIT 5""",
        (campaign_id,),
    ).fetchall()
    db.close()

    if top_contacts:
        output.append("Top Prospects:")
        status_icons = {
            "pending": "⏳",
            "invited": "📤",
            "connected": "🤝",
            "messaged": "💬",
            "replied": "📩",
            "hot_lead": "🔥",
            "review_pending": "👀",
            "opted_out": "🚫",
            "error": "❌",
        }
        for i, contact in enumerate(top_contacts):
            c = dict(contact)
            is_last = i == len(top_contacts) - 1
            prefix = "└──" if is_last else "├──"
            icon = status_icons.get(c.get("status", ""), "⚪")
            role = c.get("title", "")
            if c.get("company"):
                role += f" at {c['company']}" if role else c["company"]
            output.append(f"{prefix} {icon} {c['name']} — {role} ({stars(c.get('fit_score', 0))})")
        output.append("")

    return "\n".join(output)
