import json
import anthropic
from config import ANTHROPIC_API_KEY, CONFIDENCE_THRESHOLD, VALID_CATEGORIES

CLASSIFICATION_PROMPT = """Classify this message into exactly ONE category:
- people: mentions of people, contacts, relationships, conversations about someone
- ideas: thoughts, concepts, "what if", creative insights, brainstorming
- projects: tasks, todos, deadlines, work items, things to do
- admin: personal reminders, appointments, purchases, logistics, self-notes

Message: "{message}"

Respond with ONLY valid JSON (no markdown, no explanation):
{{"category": "people|ideas|projects|admin", "confidence": 0.0-1.0}}"""


def classify_message(message: str) -> tuple[str, float]:
    """
    Classify a message using Claude API.
    Returns (category, confidence).
    Falls back to 'inbox' if classification fails or confidence is low.
    """
    if not ANTHROPIC_API_KEY:
        print("Warning: ANTHROPIC_API_KEY not set, routing to inbox")
        return "inbox", 0.0

    try:
        client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
        response = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=100,
            messages=[
                {"role": "user", "content": CLASSIFICATION_PROMPT.format(message=message)}
            ],
        )

        result_text = response.content[0].text.strip()
        result = json.loads(result_text)

        category = result.get("category", "inbox")
        confidence = float(result.get("confidence", 0.0))

        if category not in VALID_CATEGORIES:
            return "inbox", confidence

        if confidence < CONFIDENCE_THRESHOLD:
            return "inbox", confidence

        return category, confidence

    except json.JSONDecodeError as e:
        print(f"Failed to parse Claude response: {e}")
        return "inbox", 0.0
    except anthropic.APIError as e:
        print(f"Claude API error: {e}")
        return "inbox", 0.0
    except Exception as e:
        print(f"Classification error: {e}")
        return "inbox", 0.0
