from microdot import Microdot
from models.pattern import Pattern
import json
import sys

controller = Microdot()
patterns = Pattern()

def load_pattern_definitions():
    """Load pattern definitions from pattern.json file."""
    try:
        # Try different paths for local development vs MicroPython
        paths = ['db/pattern.json', 'pattern.json', '/db/pattern.json']
        for path in paths:
            try:
                with open(path, 'r') as f:
                    return json.load(f)
            except OSError:
                continue
        return {}
    except Exception as e:
        print(f"Error loading pattern.json: {e}")
        return {}

@controller.get('/definitions')
async def get_pattern_definitions(request):
    """Get pattern definitions from pattern.json."""
    definitions = load_pattern_definitions()
    return json.dumps(definitions), 200, {'Content-Type': 'application/json'}

@controller.get('')
async def list_patterns(request):
    """List all patterns."""
    return json.dumps(patterns), 200, {'Content-Type': 'application/json'}


@controller.get('/<id>')
async def get_pattern(request, id):
    """Get a specific pattern by ID."""
    pattern = patterns.read(id)
    if pattern is not None:
        return json.dumps(pattern), 200, {'Content-Type': 'application/json'}
    return json.dumps({"error": "Pattern not found"}), 404


@controller.post('')
async def create_pattern(request):
    """Create a new pattern."""
    try:
        data = request.json or {}
        name = data.get("name", "")
        pattern_id = patterns.create(name, data.get("data", {}))
        if data:
            patterns.update(pattern_id, data)
        return json.dumps(patterns.read(pattern_id)), 201, {'Content-Type': 'application/json'}
    except Exception as e:
        return json.dumps({"error": str(e)}), 400


@controller.put('/<id>')
async def update_pattern(request, id):
    """Update an existing pattern."""
    try:
        data = request.json
        if patterns.update(id, data):
            return json.dumps(patterns.read(id)), 200, {'Content-Type': 'application/json'}
        return json.dumps({"error": "Pattern not found"}), 404
    except Exception as e:
        return json.dumps({"error": str(e)}), 400


@controller.delete('/<id>')
async def delete_pattern(request, id):
    """Delete a pattern."""
    if patterns.delete(id):
        return json.dumps({"message": "Pattern deleted successfully"}), 200
    return json.dumps({"error": "Pattern not found"}), 404
