from flask import Flask, request, jsonify
import sqlite3
import os
import json
from datetime import datetime

app = Flask(__name__)

# Database setup
DB_PATH = '/data/services-order.db'
os.makedirs('/data', exist_ok=True)

def init_db():
    """Initialize the database with orders table"""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS service_order (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id TEXT NOT NULL DEFAULT 'default',
            order_data TEXT NOT NULL,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ''')
    conn.commit()
    conn.close()

# Initialize database on startup
init_db()

@app.route('/api/order', methods=['GET'])
def get_order():
    """Get the saved service order"""
    user_id = request.args.get('user_id', 'default')
    
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute(
            'SELECT order_data FROM service_order WHERE user_id = ? ORDER BY updated_at DESC LIMIT 1',
            (user_id,)
        )
        row = cursor.fetchone()
        conn.close()
        
        if row:
            return jsonify(json.loads(row[0])), 200
        else:
            return jsonify({}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/order', methods=['POST'])
def save_order():
    """Save the service order"""
    user_id = request.json.get('user_id', 'default')
    order_data = request.json.get('order', {})
    
    if not order_data:
        return jsonify({'error': 'No order data provided'}), 400
    
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        
        # Check if user already has an order
        cursor.execute('SELECT id FROM service_order WHERE user_id = ?', (user_id,))
        existing = cursor.fetchone()
        
        if existing:
            # Update existing order
            cursor.execute(
                'UPDATE service_order SET order_data = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ?',
                (json.dumps(order_data), user_id)
            )
        else:
            # Insert new order
            cursor.execute(
                'INSERT INTO service_order (user_id, order_data) VALUES (?, ?)',
                (user_id, json.dumps(order_data))
            )
        
        conn.commit()
        conn.close()
        
        return jsonify({'success': True, 'message': 'Order saved'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/order', methods=['DELETE'])
def delete_order():
    """Delete saved order (reset to default)"""
    user_id = request.args.get('user_id', 'default')
    
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute('DELETE FROM service_order WHERE user_id = ?', (user_id,))
        conn.commit()
        conn.close()
        
        return jsonify({'success': True, 'message': 'Order deleted'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/health', methods=['GET'])
def health():
    """Health check endpoint"""
    return jsonify({'status': 'ok'}), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8082)
