#!/usr/bin/env python3
"""
Ideas Management API
"""
from flask import Flask, jsonify, request, send_file, send_from_directory
import json
import os
from datetime import datetime

app = Flask(__name__)
IDEAS_FILE = '/home/h3r7/boite_a_idees/idees.json'

# Default structure
default_data = {
    "categories": [
        {"id": "tech", "name": "Tech & IA", "color": "#7b2cbf"},
        {"id": "saas", "name": "SaaS", "color": "#2ec4b6"},
        {"id": "service", "name": "Service", "color": "#e94560"},
        {"id": "produit", "name": "Produit", "color": "#ff9f1c"},
        {"id": "invest", "name": "Investissement", "color": "#00d9ff"}
    ],
    "ideas": [
        {
            "id": 1,
            "title": "🤖 Turf Predictor AI",
            "category": "saas",
            "subcategory": "IA",
            "description": "Système automatisé de prédictions hippiques avec IA. 4 sources de données.",
            "status": "teste",
            "potential": "eleve",
            "revenue": 0,
            "created": "2026-02-21",
            "notes": "Test 24/02: 3/3 placé"
        }
    ],
    "next_id": 2
}

def load_data():
    if not os.path.exists(IDEAS_FILE):
        with open(IDEAS_FILE, 'w') as f:
            json.dump(default_data, f, indent=2)
    with open(IDEAS_FILE, 'r') as f:
        return json.load(f)

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

@app.route('/')
def index():
    return send_file('/home/h3r7/turf_scraper/dashboard.html')

@app.route('/api/ideas')
def get_ideas():
    return jsonify(load_data())

@app.route('/api/ideas', methods=['POST'])
def add_idea():
    data = load_data()
    new_idea = request.json
    new_idea['id'] = data['next_id']
    new_idea['created'] = datetime.now().strftime('%Y-%m-%d')
    data['ideas'].append(new_idea)
    data['next_id'] += 1
    save_data(data)
    return jsonify({"success": True, "id": new_idea['id']})

@app.route('/api/ideas/<int:idea_id>', methods=['PUT'])
def update_idea(idea_id):
    data = load_data()
    for i, idea in enumerate(data['ideas']):
        if idea['id'] == idea_id:
            data['ideas'][i].update(request.json)
            save_data(data)
            return jsonify({"success": True})
    return jsonify({"error": "Not found"}), 404

@app.route('/api/ideas/<int:idea_id>', methods=['DELETE'])
def delete_idea(idea_id):
    data = load_data()
    data['ideas'] = [i for i in data['ideas'] if i['id'] != idea_id]
    save_data(data)
    return jsonify({"success": True})


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

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