import os
from openai import OpenAI
from dashclaw import DashClaw
from dotenv import load_dotenv
load_dotenv()

moonshot = OpenAI(
    api_key=os.environ["MOONSHOT_API_KEY"],
    base_url="https://api.moonshot.ai/v1",
)

claw = DashClaw(
    base_url=os.environ["DASHCLAW_BASE_URL"],
    api_key=os.environ["DASHCLAW_API_KEY"],
    agent_id="moonshot-email-agent",
    agent_name="Moonshot Email Agent",
)

def send_email(recipient: str, subject: str, body: str) -> dict:
    print(f"Sending email to {recipient} with subject: {subject}")
    return {"ok": True, "recipient": recipient, "subject": subject}

def extract_action_id(action):
    if isinstance(action, dict):
        return (
            action.get("action_id")
            or action.get("id")
            or (action.get("action") or {}).get("action_id")
            or (action.get("action") or {}).get("id")
        )
    return getattr(action, "action_id", None) or getattr(action, "id", None)

def main():
    user_prompt = "Write a short follow up email to Acme asking for a meeting next week."

    completion = moonshot.chat.completions.create(
        model="kimi-k2-turbo-preview",
        messages=[
            {
                "role": "system",
                "content": (
                    "You are Kimi, an AI assistant provided by Moonshot AI. "
                    "You are proficient in Chinese and English conversations. "
                    "You provide users with safe, helpful, and accurate answers."
                ),
            },
            {"role": "user", "content": user_prompt},
        ],
        temperature=0.6,
    )

    drafted_email = completion.choices[0].message.content

    guard = claw.guard({
        "action_type": "message",
        "risk_score": 72,
        "systems_touched": ["email", "moonshot_api"],
        "reversible": False,
        "declared_goal": "Draft and send outbound follow up email to a prospect",
    })

    print("Guard result:", guard)

    if isinstance(guard, dict) and guard.get("decision") in ["block", "require_approval"]:
        print("DashClaw stopped the action:", guard)
        return

    action = claw.create_action(
        "message",
        declared_goal="Send outbound follow up email to Acme",
        reasoning="User requested a follow up email generated by Moonshot.",
        systems_touched=["email", "moonshot_api"],
        input_summary=user_prompt,
        reversible=False,
        risk_score=72,
        confidence=84,
    )

    print("Action response:", action)

    action_id = extract_action_id(action)
    if not action_id:
        raise RuntimeError(f"Could not determine action_id from response: {action}")

    claw.register_assumption({
        "action_id": action_id,
        "assumption": "The recipient is a valid business contact and outreach is authorized.",
        "basis": "User initiated the request and provided the business context.",
        "validated": False,
    })

    try:
        result = send_email(
            recipient="team@acme.com",
            subject="Quick follow up",
            body=drafted_email,
        )

        claw.update_outcome(action_id, {
            "status": "completed",
            "output_summary": f"Email sent successfully to {result['recipient']}",
        })

        print("Success. Check DashClaw dashboard for the action trace:", action_id)

    except Exception as e:
        claw.update_outcome(action_id, {
            "status": "failed",
            "output_summary": f"Email send failed: {str(e)}",
        })
        raise

if __name__ == "__main__":
    main()