#!/usr/bin/env python3
"""
Agent Chat API - Communications entre agents H3R7Tech
"""
from flask import Flask, jsonify, request, send_from_directory
from flask_cors import CORS
import json
import os
from datetime import datetime

app = Flask(__name__)
CORS(app)

CHAT_FILE = '/home/h3r7/turf_scraper/agent_chat.json'

def load_chat():
    if not os.path.exists(CHAT_FILE):
        data = {"messages": []}
        with open(CHAT_FILE, 'w') as f:
            json.dump(data, f, indent=2)
        return data
    with open(CHAT_FILE, 'r') as f:
        return json.load(f)

def save_chat(data):
    with open(CHAT_FILE, 'w') as f:
        json.dump(data, f, indent=2)

@app.route('/')
def index():
    return send_from_directory('/home/h3r7/turf_scraper', 'agent_chat.html')

@app.route('/api/messages', methods=['GET'])
def get_messages():
    data = load_chat()
    limit = request.args.get('limit', 50)
    return jsonify(data['messages'][-int(limit):])

@app.route('/api/messages', methods=['POST'])
def add_message():
    data = load_chat()
    req = request.json
    
    message = {
        'id': len(data['messages']) + 1,
        'agent': req.get('agent', 'system'),
        'type': req.get('type', 'info'),  # info, warning, error, success
        'content': req.get('content', ''),
        'timestamp': datetime.now().isoformat()
    }
    data['messages'].append(message)
    save_chat(data)
    return jsonify({'success': True, 'message': message})

@app.route('/api/messages', methods=['DELETE'])
def clear_messages():
    data = {'messages': []}
    save_chat(data)
    return jsonify({'success': True})

@app.route('/api/stats', methods=['GET'])
def get_stats():
    data = load_chat()
    messages = data['messages']
    
    stats = {
        'total': len(messages),
        'par_agent': {},
        'par_type': {}
    }
    
    for m in messages:
        agent = m.get('agent', 'unknown')
        stats['par_agent'][agent] = stats['par_agent'].get(agent, 0) + 1
        
        type_msg = m.get('type', 'info')
        stats['par_type'][type_msg] = stats['par_type'].get(type_msg, 0) + 1
    
    return jsonify(stats)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8771, debug=False)
