TOOL_NAME = "analyze_whatsapp_history"
TOOL_DESCRIPTION = """Analyse a WhatsApp chat export (.txt) and return conversation statistics: total messages, unique participants, top-5 most active senders, and daily activity for the last 7 days."""
TOOL_ARGS = '{"file_path": {"type": "string", "description": "Path to the WhatsApp chat export .txt file"}, "max_messages": {"type": "integer", "default": 1000, "description": "Maximum number of messages to parse"}}'

import re
from collections import Counter
from datetime import datetime
import os
from tools._std import tool_ok, tool_error

_MSG_RE = re.compile(r'(\d{1,2}/\d{1,2}/\d{2,4}),\s*(\d{1,2}:\d{2})\s*-\s*([^:]+):\s*(.+)$')
_DATE_FMTS = ['%d/%m/%y', '%d/%m/%Y']

def run(args: dict) -> str:
    file_path = args.get('file_path', '')
    max_messages = args.get('max_messages', 1000)
    
    if not file_path:
        return tool_error("Geen bestandspad opgegeven. Gebruik: {\"file_path\": \"pad/naar/chat.txt\"}")
    
    if not os.path.exists(file_path):
        return tool_error(f"Bestand niet gevonden: {file_path}")
    
    # Lees het bestand
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    # Regex voor WhatsApp formaat (DD/MM/YY, HH:MM - Naam: Bericht)
    messages = []
    users = Counter()
    dates = []
    
    for line in lines[:max_messages]:
        match = _MSG_RE.match(line.strip())
        if match:
            date_str, time_str, user, message = match.groups()
            date = None
            for fmt in _DATE_FMTS:
                try:
                    date = datetime.strptime(date_str, fmt)
                    break
                except ValueError:
                    continue
            if date:
                messages.append({'user': user.strip(), 'message': message, 'date': date})
                users[user.strip()] += 1
                dates.append(date.strftime('%Y-%m-%d'))
    
    if not messages:
        return tool_error("Geen geldige WhatsApp berichten gevonden. Zorg voor .txt export met formaat: DD/MM/YY, HH:MM - Naam: Bericht")
    
    # Statistieken
    total = len(messages)
    unique_users = len(users)
    top_users = users.most_common(5)
    
    # Date range
    date_counts = Counter(dates)
    date_range = f"{min(dates)} tot {max(dates)}"
    
    # Resultaat
    result = f"📊 WhatsApp Chat Analyse\n"
    result += f"========================\n"
    result += f"Totaal berichten: {total}\n"
    result += f"Unieke deelnemers: {unique_users}\n"
    result += f"Datumreeks: {date_range}\n\n"
    
    result += f"👥 Top 5 meest actieve deelnemers:\n"
    for i, (user, count) in enumerate(top_users, 1):
        pct = (count / total) * 100
        result += f"  {i}. {user}: {count} berichten ({pct:.1f}%)\n"
    
    result += f"\n📅 Activiteit per dag (laatste 7):\n"
    for date, count in sorted(date_counts.items())[-7:]:
        result += f"  {date}: {count} berichten\n"
    
    return tool_ok({
        "total_messages": total,
        "unique_users": unique_users,
        "top_users": [{"name": u, "count": c} for u, c in top_users],
        "date_range": date_range,
    }, result)
