"""GTM mode tools — org-scoped operations for campaign managers.

These tools do NOT require a repo_id. They're used by campaign managers,
marketing ops, and non-technical users in Claude Desktop.
"""

from __future__ import annotations

from mcp.server import FastMCP

from g8_mcp_server.client import G8Client, format_result


def register(server: FastMCP, client: G8Client) -> None:
    """Register GTM-mode tools (org-scoped, no repo_id)."""

    # -- Campaigns --

    @server.tool()
    async def g8_list_campaigns(page: int = 1, limit: int = 50) -> str:
        """List all campaigns in your organization.

        Returns campaign names, categories, goals, and statuses.

        Args:
            page: Page number (default 1)
            limit: Items per page (default 50, max 200)
        """
        result = await client.get("/campaigns", {"page": page, "limit": limit})
        return format_result(result)

    @server.tool()
    async def g8_get_campaign(campaign_id: str) -> str:
        """Get full details for a specific campaign.

        Returns the campaign brief, core concept, primary hook, target persona,
        channel strategy, and list of generated documents.

        Args:
            campaign_id: Campaign ID from g8_list_campaigns
        """
        result = await client.get(f"/campaigns/{campaign_id}")
        return format_result(result)

    @server.tool()
    async def g8_get_campaign_document(campaign_id: str, document_id: str) -> str:
        """Get the full content of a campaign document.

        Use g8_get_campaign first to see the list of documents, then call
        this tool with a specific document_id to read its body content.

        Args:
            campaign_id: Campaign ID
            document_id: Document ID from the campaign's documents list
        """
        result = await client.get(f"/campaigns/{campaign_id}/documents/{document_id}")
        return format_result(result)

    @server.tool()
    async def g8_create_campaign(
        name: str,
        category: str = "Outbound",
        brief: str | None = None,
        core_concept: str | None = None,
        primary_hook: str | None = None,
        target_persona: str | None = None,
        goal: str | None = None,
    ) -> str:
        """Create a new campaign from scratch.

        Returns the new campaign ID and slug. The campaign starts in 'draft'
        status — use g8_launch_campaign to activate it.

        Args:
            name: Campaign name (required)
            category: Category — Outbound, Social Proof, Trigger, Persona,
                      Thought Leadership, or Insight
            brief: Campaign brief describing the strategy
            core_concept: Core concept text
            primary_hook: Primary hook text
            target_persona: Target persona description
            goal: Goal — awareness, consideration, or decision
        """
        body = {
            k: v for k, v in {
                "name": name, "category": category, "brief": brief,
                "core_concept": core_concept, "primary_hook": primary_hook,
                "target_persona": target_persona, "goal": goal,
            }.items() if v is not None
        }
        result = await client.post("/campaigns", body)
        return format_result(result)

    @server.tool()
    async def g8_update_campaign(
        campaign_id: str,
        name: str | None = None,
        brief: str | None = None,
        core_concept: str | None = None,
        primary_hook: str | None = None,
        target_persona: str | None = None,
        category: str | None = None,
        goal: str | None = None,
    ) -> str:
        """Update a campaign's content — name, brief, hook, persona, etc.

        Only provide the fields you want to change.

        Args:
            campaign_id: Campaign ID to update
            name: New campaign name
            brief: New campaign brief
            core_concept: New core concept
            primary_hook: New primary hook text
            target_persona: New target persona description
            category: New category (e.g. Outbound, Social Proof, Trigger)
            goal: New goal (e.g. awareness, consideration, decision)
        """
        body = {
            k: v for k, v in {
                "name": name, "brief": brief, "core_concept": core_concept,
                "primary_hook": primary_hook, "target_persona": target_persona,
                "category": category, "goal": goal,
            }.items() if v is not None
        }
        result = await client.patch(f"/campaigns/{campaign_id}", body)
        return format_result(result)

    @server.tool()
    async def g8_launch_campaign(campaign_id: str) -> str:
        """Launch a campaign to begin outbound execution.

        IMPORTANT: This starts sending outreach to real contacts. Always confirm
        with the user before calling this tool.

        Args:
            campaign_id: Campaign ID to launch
        """
        result = await client.post(f"/campaigns/{campaign_id}/launch")
        return format_result(result)

    # -- Knowledge Base --

    @server.tool()
    async def g8_search_kb(query: str) -> str:
        """Search the GTM knowledge base.

        The knowledge base contains strategic documents covering company
        profile, ICP profiles, buyer personas, messaging, competitive analysis,
        market intelligence, content strategy, and sales enablement.

        Args:
            query: Search query (e.g. "ICP for enterprise buyers", "objection handling")
        """
        result = await client.post("/kb/search", {"query": query})
        return format_result(result)

    @server.tool()
    async def g8_list_kb_documents() -> str:
        """List all documents in the GTM knowledge base.

        Returns document titles grouped by section (brand, market, audience,
        offer, messaging, intelligence, research). Use this to browse what's
        available before searching.
        """
        result = await client.get("/kb")
        return format_result(result)
