"""Tools 26-27: scheduler_status + toggle_scheduler.

Provides visibility into and control over the autonomous scheduler.
Supports both local (in-process) and cloud (backend) scheduling modes.
"""

from __future__ import annotations

import logging
import time
from datetime import datetime
from typing import Any

from ..config import is_scheduler_enabled, set_scheduler_enabled, is_backend_mode
from ..db.queries import get_scheduler_stats

logger = logging.getLogger(__name__)


async def run_scheduler_status() -> str:
    """Show scheduler status, pending jobs, and recent activity.

    If in backend mode, also shows cloud scheduler status.
    """
    enabled = is_scheduler_enabled()
    stats = get_scheduler_stats()
    now = int(time.time())

    # ── Header ──
    status_icon = "\u2601\ufe0f" if enabled else "\u23f8\ufe0f"
    lines = [
        f"# {status_icon} Scheduler {'Enabled' if enabled else 'Disabled'}",
        "",
    ]

    if not enabled:
        lines.append(
            "The autonomous scheduler is currently **off**.\n"
            "Enable it with: `scheduler(action='toggle', enabled=True)`\n\n"
            "When enabled, the scheduler will automatically:\n"
            "- Send invitations to pending prospects (autopilot campaigns)\n"
            "- Send follow-ups on schedule (1, 7, 14, 21, 28 days)\n"
            "- Check for replies every 5 minutes\n"
            "- Engage with prospect posts every 30 minutes\n"
            "- Respect rate limits, working hours, and daily caps"
        )
        # Still show cloud status if available
        cloud_section = await _cloud_status_section()
        if cloud_section:
            lines.append("")
            lines.append(cloud_section)
        return "\n".join(lines)

    # ── Job Counts ──
    counts = stats.get("counts", [])
    if counts:
        lines.append("## Job Queue")
        lines.append("")
        lines.append("| Status | Type | Count |")
        lines.append("|--------|------|-------|")
        for row in counts:
            status = row["status"]
            job_type = row["job_type"]
            cnt = row["cnt"]
            icon = {"pending": "\u23f3", "running": "\U0001f504", "completed": "\u2705", "failed": "\u274c"}.get(status, "")
            lines.append(f"| {icon} {status} | {job_type} | {cnt} |")
        lines.append("")
    else:
        lines.append("\U0001f4ed No jobs in queue\n")

    # ── Next Scheduled ──
    next_jobs = stats.get("next_jobs", [])
    if next_jobs:
        lines.append("## Next Scheduled")
        lines.append("")
        for job in next_jobs:
            scheduled = job["scheduled_at"]
            delta = scheduled - now
            if delta > 0:
                mins = delta // 60
                when = f"in {mins} min" if mins > 0 else "now"
            else:
                when = "overdue"

            job_type = job["job_type"]
            outreach = job.get("outreach_id", "")
            target = f" (outreach: {outreach[:8]}...)" if outreach else ""
            lines.append(f"- **{job_type}** {when}{target}")
        lines.append("")

    # ── Recent Activity ──
    recent = stats.get("recent", [])
    if recent:
        lines.append("## Recent Activity")
        lines.append("")
        for job in recent[:5]:
            completed = job.get("completed_at", 0)
            ago = (now - completed) // 60 if completed else 0
            status = job["status"]
            icon = "\u2705" if status == "completed" else "\u274c"
            error = job.get("error", "")
            error_text = f" \u2014 {error[:50]}" if error else ""
            lines.append(
                f"- {icon} **{job['job_type']}** {ago} min ago{error_text}"
            )
        lines.append("")

    # ── Brand Automation ──
    brand_section = _brand_automation_section(stats)
    if brand_section:
        lines.append(brand_section)
        lines.append("")

    # ── Cloud Status ──
    cloud_section = await _cloud_status_section()
    if cloud_section:
        lines.append(cloud_section)

    # ── Quick Actions ──
    lines.append("## Quick Actions")
    lines.append("- `scheduler(action='toggle', enabled=False)` \u2014 pause the scheduler")
    lines.append("- `scheduler(action='toggle', enabled=True, cloud=True)` \u2014 enable cloud 24/7 scheduling")
    lines.append("- `show_status()` \u2014 view campaign dashboard")
    lines.append("- `campaign(action='emergency_stop')` \u2014 pause all campaigns immediately")

    return "\n".join(lines)


def _brand_automation_section(stats: dict[str, Any]) -> str:
    """Build brand automation status section if brand plan exists."""
    from ..db.queries import get_setting
    from ..formatter import progress_bar

    brand_plan = get_setting("brand_strategy")
    if not brand_plan or not isinstance(brand_plan, dict) or not brand_plan.get("weeks"):
        return ""

    total = sum(len(w.get("actions", [])) for w in brand_plan.get("weeks", []))
    done = sum(
        1 for w in brand_plan.get("weeks", [])
        for a in w.get("actions", []) if a.get("status") == "completed"
    )

    lines = [
        "## \U0001f3af Brand Automation",
        "",
        f"**Progress**: {done}/{total} actions {progress_bar(done, total, 15)}",
    ]

    # Show next scheduled brand jobs from stats
    next_jobs = stats.get("next_jobs", [])
    brand_jobs = [j for j in next_jobs if j.get("job_type", "").startswith("brand_")]
    if brand_jobs:
        now = int(time.time())
        for job in brand_jobs[:3]:
            delta = job["scheduled_at"] - now
            if delta > 0:
                mins = delta // 60
                when = f"in {mins} min" if mins > 0 else "now"
            else:
                when = "overdue"
            lines.append(f"- Next **{job['job_type']}** {when}")
    else:
        if done < total:
            lines.append("- Posts + engagements run automatically via scheduler")
        else:
            lines.append("- All actions complete! Re-analysis scheduled at 28-day mark")

    # Show automation status
    lines.append("")
    lines.append("Automation runs: posts (~2-3/week), engagements (~5/day), re-analyze (every 28d)")

    return "\n".join(lines)


async def _cloud_status_section() -> str:
    """Build cloud scheduler status section if in backend mode."""
    if not is_backend_mode():
        return ""

    try:
        from ..services.cloud_sync import get_cloud_scheduler_status

        cloud = await get_cloud_scheduler_status()
        if "error" in cloud:
            return f"## \u2601\ufe0f Cloud Scheduler\n\n\u26a0\ufe0f {cloud['error']}"

        cloud_enabled = cloud.get("enabled", False)
        pending = cloud.get("pending_jobs", 0)
        campaigns = cloud.get("campaigns", [])

        icon = "\U0001f7e2" if cloud_enabled else "\u23f8\ufe0f"
        lines = [
            f"## \u2601\ufe0f Cloud Scheduler {icon} {'Enabled' if cloud_enabled else 'Disabled'}",
            "",
        ]

        if cloud_enabled:
            lines.append(f"**Pending jobs**: {pending}")
            if campaigns:
                lines.append(f"**Cloud campaigns**: {len(campaigns)}")
                for c in campaigns[:5]:
                    lines.append(f"  - {c.get('name', 'Unknown')} ({c.get('status', '?')})")
            lines.append("")
            lines.append("The backend processes outreach every 5 min, 24/7.")

            # Recent cloud activity
            recent = cloud.get("recent_activity", [])
            if recent:
                lines.append("")
                lines.append("**Recent cloud activity:**")
                for job in recent[:3]:
                    jtype = job.get("job_type", "?")
                    status = job.get("status", "?")
                    icon = "\u2705" if status == "completed" else "\u274c"
                    lines.append(f"  {icon} {jtype} ({status})")
        else:
            lines.append(
                "Cloud scheduling is off. Enable with:\n"
                "`toggle_scheduler(enabled=True, cloud=True)`"
            )

        return "\n".join(lines)
    except Exception as e:
        logger.debug("Cloud status check failed: %s", e)
        return ""


async def run_toggle_scheduler(enabled: bool, cloud: bool = False) -> str:
    """Enable or disable the autonomous scheduler.

    Args:
        enabled: Whether to enable (True) or disable (False).
        cloud: If True, toggle the cloud (backend) scheduler for 24/7 operation.
               If False, toggle the local (in-process) scheduler.
    """
    if cloud:
        from ..services.cloud_sync import toggle_cloud_scheduler
        return await toggle_cloud_scheduler(enabled)

    # Local scheduler toggle (unchanged)
    was_enabled = is_scheduler_enabled()

    if enabled == was_enabled:
        state = "enabled" if enabled else "disabled"
        return f"Scheduler is already {state}. No change made."

    set_scheduler_enabled(enabled)

    if enabled:
        return (
            "\U0001f7e2 **Scheduler enabled!**\n\n"
            "The scheduler will now automatically process outreach for **autopilot** campaigns:\n"
            "- Send invitations (20-40 min randomized delays)\n"
            "- Send follow-ups (on schedule: day 1, 7, 14, 21, 28)\n"
            "- Check for replies (every 5 min)\n"
            "- Engage with prospect posts (every 30 min)\n\n"
            "All actions respect working hours, rate limits, and daily caps.\n"
            "Copilot campaigns still require manual approval.\n\n"
            "Use `scheduler(action='status')` to monitor progress.\n\n"
            "\U0001f4a1 **Tip**: For 24/7 scheduling (even when laptop is off), use:\n"
            "`scheduler(action='toggle', enabled=True, cloud=True)`"
        )
    else:
        return (
            "\u23f8\ufe0f **Scheduler disabled.**\n\n"
            "Autonomous outreach has been paused. No new jobs will be scheduled.\n"
            "Already-running jobs will complete, but no new ones will start.\n\n"
            "Your campaigns are still active \u2014 you can manually send with:\n"
            "- `generate_and_send()` \u2014 send an invitation\n"
            "- `send_message(action='followup')` \u2014 send a follow-up\n"
            "- `check_replies()` \u2014 check for replies\n\n"
            "Use `scheduler(action='toggle', enabled=True)` to re-enable."
        )
