"""Onboarding tools — register, verify OTP, KYC, create agent.

These tools guide a new user through the full Amrood signup flow:
  1. amrood_register  → sends OTP to phone
  2. amrood_verify    → verifies OTP, creates owner account
  3. amrood_kyc       → submits PAN + bank details
  4. amrood_create_agent → creates an agent and returns the API key
"""

from __future__ import annotations

import json

from mcp.server.fastmcp import FastMCP

from amrood_mcp.api_client import AmroodAPI
from amrood_mcp.auth import AuthState


def register_onboarding_tools(mcp: FastMCP, api: AmroodAPI, auth: AuthState):
    """Register onboarding tools on the MCP server."""

    @mcp.tool()
    async def amrood_register(phone: str, name: str = "") -> str:
        """Start Amrood registration by sending an OTP to the user's phone.

        This is Step 1 of onboarding. After calling this, ask the user
        for the 6-digit OTP code they receive, then call amrood_verify.

        Args:
            phone: 10-digit Indian phone number (e.g. "9876543210")
            name: User's name (required for new accounts, optional for existing)
        """
        resp = await api.post("/v1/auth/send-otp", json={"phone": phone})
        if resp.status_code >= 400:
            try:
                err = resp.json()
            except Exception:
                err = resp.text
            return f"Registration failed ({resp.status_code}): {json.dumps(err)}"

        data = resp.json()
        # Store name for the verify step
        auth._pending_name = name
        return json.dumps({
            "status": "otp_sent",
            "otp_id": data.get("otp_id"),
            "phone": phone,
            "next_step": "Ask the user for the 6-digit OTP code, then call amrood_verify.",
        }, indent=2)

    @mcp.tool()
    async def amrood_verify(phone: str, code: str, name: str = "") -> str:
        """Verify the OTP code and create/login the Amrood account.

        This is Step 2 of onboarding. After successful verification,
        check the kyc_status. If not "verified", call amrood_kyc next.

        Args:
            phone: Same 10-digit phone number used in amrood_register
            code: The 6-digit OTP code the user received
            name: User's full name (required for new accounts)
        """
        if not name:
            name = getattr(auth, "_pending_name", "") or ""

        resp = await api.post("/v1/auth/verify-otp", json={
            "phone": phone,
            "code": code,
            "name": name,
        })
        if resp.status_code >= 400:
            try:
                err = resp.json()
            except Exception:
                err = resp.text
            return f"Verification failed ({resp.status_code}): {json.dumps(err)}"

        data = resp.json()
        session_token = data.get("session_token")
        if session_token:
            auth.set_session(session_token, data.get("owner_id", ""))

        kyc_status = data.get("kyc_status", "pending")
        if kyc_status == "verified":
            next_step = "KYC already verified. Call amrood_create_agent to create an agent."
        else:
            next_step = "Call amrood_kyc with PAN and bank details to complete verification."

        return json.dumps({
            "status": "authenticated",
            "owner_id": data.get("owner_id"),
            "name": data.get("name"),
            "kyc_status": kyc_status,
            "is_new": data.get("is_new"),
            "next_step": next_step,
        }, indent=2)

    @mcp.tool()
    async def amrood_kyc(
        pan: str,
        bank_account: str | None = None,
        bank_ifsc: str | None = None,
        upi_id: str | None = None,
        email: str | None = None,
    ) -> str:
        """Submit KYC details — PAN card and bank account or UPI ID.

        This is Step 3 of onboarding. Requires a valid PAN number and
        either bank account + IFSC or a UPI ID for settlement.

        Args:
            pan: PAN card number (e.g. "ABCDE1234F")
            bank_account: Bank account number (6-40 digits)
            bank_ifsc: Bank IFSC code (e.g. "HDFC0001234")
            upi_id: UPI VPA as alternative to bank account (e.g. "name@upi")
            email: Optional email address
        """
        if not auth.has_session:
            return "Error: Not authenticated. Call amrood_register and amrood_verify first."

        body: dict = {"pan": pan.upper()}
        if bank_account:
            body["bank_account"] = bank_account
        if bank_ifsc:
            body["bank_ifsc"] = bank_ifsc.upper()
        if upi_id:
            body["upi_id"] = upi_id
        if email:
            body["email"] = email

        resp = await api.post("/api/web/kyc", json=body, use_session=True)
        if resp.status_code >= 400:
            try:
                err = resp.json()
            except Exception:
                err = resp.text
            return f"KYC submission failed ({resp.status_code}): {json.dumps(err)}"

        data = resp.json()
        kyc_status = data.get("kyc_status", "pending")

        if kyc_status == "verified":
            next_step = "KYC verified! Call amrood_create_agent to create your agent."
        else:
            next_step = "KYC not yet verified. Check that PAN is valid and bank/UPI details are correct."

        return json.dumps({
            "owner_id": data.get("owner_id"),
            "kyc_status": kyc_status,
            "next_step": next_step,
        }, indent=2)

    @mcp.tool()
    async def amrood_create_agent(name: str) -> str:
        """Create a new Amrood agent and get its API key.

        This is the final step of onboarding. Returns the agent_id and
        agent_key. The agent_key should be saved — it's shown only once.
        After creation, all agent tools (balance, pay, etc.) become available.

        Args:
            name: A name for the agent (e.g. "My Research Agent")
        """
        if not auth.has_session:
            return "Error: Not authenticated. Call amrood_register and amrood_verify first."

        resp = await api.post("/api/web/agents", json={"name": name}, use_session=True)
        if resp.status_code >= 400:
            try:
                err = resp.json()
            except Exception:
                err = resp.text
            return f"Agent creation failed ({resp.status_code}): {json.dumps(err)}"

        data = resp.json()
        if not data.get("ok"):
            return f"Agent creation failed: {data.get('error', 'Unknown error')}"

        agent_key = data.get("agent_key", "")
        agent_id = data.get("agent_id", "")

        auth.set_agent(agent_key, agent_id)

        return json.dumps({
            "status": "agent_created",
            "agent_id": agent_id,
            "agent_key": agent_key,
            "vendor_id": data.get("vendor_id"),
            "important": "Save the agent_key — it is shown only once. "
                         "Set it as AMROOD_AGENT_KEY in your MCP config for future sessions.",
            "next_step": "Agent is ready. Use amrood_fund to add balance, then amrood_pay to pay other agents.",
        }, indent=2)
