"""Tool: archive_campaign — Mark a campaign as completed/archived.

Archived campaigns stop receiving outreach and move to completed status.
They remain viewable via show_status(campaign_id=...) for historical reference.
"""

from __future__ import annotations

import logging

from ..db.queries import (
    get_campaign,
    get_setting,
    list_campaigns,
    log_action,
    update_campaign,
)

logger = logging.getLogger(__name__)


async def run_archive_campaign(campaign_id: str = "") -> str:
    """Archive a campaign, setting its status to 'completed'.

    If no campaign_id is provided, archives the first non-completed campaign found.
    """

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

    # Find the campaign to archive
    if campaign_id:
        campaign = get_campaign(campaign_id)
        if not campaign:
            return f"Campaign not found: {campaign_id}"
    else:
        campaigns = list_campaigns()
        # Pick the first non-completed campaign
        candidates = [c for c in campaigns if c.get("status") != "completed"]
        if not candidates:
            return (
                "No campaigns available to archive.\n\n"
                "All campaigns are already archived, or no campaigns exist.\n"
                "Use show_status() to see all campaigns."
            )
        campaign = candidates[0]
        campaign_id = campaign["id"]

    # Check current status
    status = campaign.get("status", "")
    if status == "completed":
        return (
            f"Campaign '{campaign['name']}' is already archived.\n\n"
            f"View it with: show_status(campaign_id=\"{campaign_id}\")"
        )

    # Archive it
    update_campaign(campaign_id, status="completed")
    log_action(
        "campaign_archived",
        details={
            "campaign_id": campaign_id,
            "campaign_name": campaign["name"],
            "previous_status": status,
        },
    )
    logger.info(f"Archived campaign {campaign_id}: {campaign['name']}")

    return (
        f"Campaign '{campaign['name']}' has been archived.\n\n"
        "It will no longer appear in active campaign views.\n"
        "No further outreach will be sent for this campaign.\n\n"
        f"To view archived campaign details: show_status(campaign_id=\"{campaign_id[:8]}...\")\n"
        "To create a new campaign: create_campaign(\"your target description\")"
    )
