from django.db import models
from django.http import JsonResponse
from flask import Flask, request, jsonify
from fastapi import FastAPI
from sqlalchemy.orm import Session
import requests
import json


class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=10, decimal_places=2)


def product_list_view(request):
    """Clean: uses .count() and slice."""
    qs = Product.objects.filter(active=True)
    count = qs.count()
    items = qs[:10]
    return JsonResponse({"count": count})


def related_clean_view(request):
    """Clean: uses select_related."""
    orders = Order.objects.select_related("customer").all()
    for order in orders:
        print(order.customer.name)


def bulk_create_clean(request):
    """Clean: uses bulk_create."""
    products = [Product(name=n) for n in request.POST.getlist("names")]
    Product.objects.bulk_create(products)


app = Flask(__name__)


@app.route("/parse", methods=["POST"])
def flask_clean_view():
    """Clean: parses body once."""
    data = request.get_json()
    return jsonify(data)


@app.route("/db")
def flask_db_clean():
    """Clean: no inline connection."""
    return jsonify({"ok": True})


fastapi_app = FastAPI()


@fastapi_app.get("/async")
async def fastapi_async_view():
    """Clean: async handler."""
    return {"data": "ok"}


def sqlalchemy_clean():
    """Clean: uses session properly."""
    session = Session()
    try:
        result = session.query(Product).all()
    finally:
        session.close()


def clean_handler(request):
    """Clean: single upstream call with timeout."""
    resp = requests.get("https://api.example.com/data", timeout=10)
    resp.raise_for_status()
    return resp.json()


def process_internal():
    """Clean: not a handler, plain utility."""
    data = {"key": "value"}
    return json.dumps(data)
