#!/usr/bin/env python3
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)

CRM_FILE = '/home/h3r7/turf_scraper/crm_prospects.json'

def load_crm():
    if not os.path.exists(CRM_FILE):
        data = {'prospects': [], 'last_id': 0}
        with open(CRM_FILE, 'w') as f:
            json.dump(data, f, indent=2)
        return data
    with open(CRM_FILE, 'r') as f:
        return json.load(f)

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

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

@app.route('/api/prospects', methods=['GET'])
def get_prospects():
    data = load_crm()
    return jsonify(data)

@app.route('/api/prospects', methods=['POST'])
def add_prospect():
    data = load_crm()
    req = request.json
    
    # Generate string ID if not provided
    prospect_id = req.get('id') or f"prospect_{data['last_id'] + 1}"
    data['last_id'] += 1
    
    prospect = {
        'id': prospect_id,
        'nom': req.get('nom', ''),
        'entreprise': req.get('entreprise', ''),
        'tel': req.get('tel', ''),
        'email': req.get('email', ''),
        'secteur': req.get('secteur', ''),
        'statut': req.get('statut', 'nouveau'),
        'score': req.get('score', 0),
        'notes': req.get('notes', ''),
        'adresse': req.get('adresse', ''),
        'ville': req.get('ville', ''),
        'categorie': req.get('categorie', ''),
        'created': datetime.now().strftime('%Y-%m-%d')
    }
    data['prospects'].append(prospect)
    save_crm(data)
    return jsonify({'success': True, 'prospect': prospect})

@app.route('/api/prospects/<path:prospect_id>', methods=['PUT'])
def update_prospect(prospect_id):
    data = load_crm()
    req = request.json
    
    for p in data['prospects']:
        if str(p['id']) == str(prospect_id):
            p.update(req)
            save_crm(data)
            return jsonify({'success': True, 'prospect': p})
    
    return jsonify({'error': 'Prospect non trouvé'}), 404

@app.route('/api/prospects/<path:prospect_id>', methods=['DELETE'])
def delete_prospect(prospect_id):
    data = load_crm()
    initial_len = len(data['prospects'])
    data['prospects'] = [p for p in data['prospects'] if str(p['id']) != str(prospect_id)]
    
    if len(data['prospects']) < initial_len:
        save_crm(data)
        return jsonify({'success': True})
    
    return jsonify({'error': 'Prospect non trouvé'}), 404

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