# from django.shortcuts import render
# from django.utils import timezone
# from django.http import HttpRequest, HttpResponse
# from datetime import datetime
# from typing import Dict, Any, Optional
# from iching.utils import bz as bazi, liuyao
# import json
# from liuyao.models import liuyao as lymodel
# from django.views.decorators.http import require_http_methods
# from django.core.exceptions import ValidationError
# from django.views.decorators.csrf import csrf_protect

# def parse_datetime_from_request(data: Dict[str, Any]) -> datetime:
#     """Parse datetime from request data or return current time if using current time."""
#     if data.get('usecur'):
#         return datetime.now(bazi.gMYTimezone)
    
#     try:
#         year = int(data.get('year'))
#         month = int(data.get('month'))
#         day = int(data.get('day'))
#         time = data.get('time', '').split(':')
#         if len(time) != 2:
#             raise ValidationError("Invalid time format")
        
#         hour = int(time[0])
#         minute = int(time[1])
        
#         return datetime(year, month, day, hour, minute)
#     except (ValueError, TypeError, AttributeError) as e:
#         raise ValidationError(f"Invalid date/time format: {str(e)}")

# def calculate_iching_data(date: datetime, yao_inputs: Dict[str, str], question: str) -> Dict[str, Any]:
#     """Calculate I-Ching related data based on the given inputs."""
#     # Calculate bazi
#     bz = bazi.getDateTimeGodEarthStem(
#         date.year, date.month, date.day, date.hour, date.minute
#     )
#     bz['date'] = date.strftime('%Y-%m-%d %H:%M:%S')
#     bz['empty'] = bazi.calcEarthEmpty(bz['day']['g'], bz['day']['e'])
    
#     # Calculate 6 God
#     god6 = liuyao.calc6God(bz['day']['g'])
    
#     # Calculate 6 Yao
#     ly = liuyao.calc6Yao(
#         yao_inputs.get('l1'), yao_inputs.get('l2'),
#         yao_inputs.get('l3'), yao_inputs.get('l4'),
#         yao_inputs.get('l5'), yao_inputs.get('l6')
#     )
    
#     # Calculate Relationship
#     rel = liuyao.calcRelationship(ly, bz)
    
#     return {
#         'question': question,
#         'bz': bz,
#         'god6': god6,
#         'ly': ly,
#         'rel': rel,
#     }

# def save_liuyao_reading(data: Dict[str, Any], yao: list[str], question: str, reading: str) -> lymodel:
#     """Save liuyao reading to database."""
#     return lymodel.objects.create(
#         qdate=data['bz']['date'],
#         question=question,
#         y1=yao[0],
#         y2=yao[1],
#         y3=yao[2],
#         y4=yao[3],
#         y5=yao[4],
#         y6=yao[5],
#         reading=reading,
#         data=data
#     )

# @csrf_protect
# @require_http_methods(["POST"])
# def lyresult(request: HttpRequest) -> HttpResponse:
#     """View function for saving and displaying liuyao reading results."""
#     context = {}
    
#     try:
#         data = json.loads(request.POST.get('gua', '{}'))
#         if not data:
#             raise ValidationError("Invalid gua data")
            
#         yao = request.POST.get('yao', '').split('|')
#         if len(yao) != 6:
#             raise ValidationError("Invalid yao data")
            
#         question = request.POST.get('question', '')
#         reading = request.POST.get('rcomment', '')
        
#         save_liuyao_reading(data, yao, question, reading)
#         context['success'] = True
        
#     except (json.JSONDecodeError, ValidationError, Exception) as e:
#         context['error'] = str(e)
    
#     return render(request, 'lyresult.html', context=context)

from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required

@login_required
def set_pagination_preference(request):
    """Save user's pagination preference to session"""
    if request.method == 'POST':
        app = request.POST.get('app')  # 'bazi' or 'liuyao'
        per_page = request.POST.get('per_page')
        
        if app and per_page and per_page.isdigit() and 5 <= int(per_page) <= 100:
            # Store in session
            request.session[f'{app}_items_per_page'] = int(per_page)
            
    # Redirect back to the referring page
    return redirect(request.META.get('HTTP_REFERER', 'home'))