import os
import json
from supabase import create_client, Client
import boto3
import pandas as pd
from io import BytesIO
from datetime import datetime, timedelta

def lambda_handler(event, context):
    # Initialize Supabase client 
    # Change to paramenter store
    url: str = os.environ.get("SUPABASE_URL")
    key: str = os.environ.get("SUPABASE_KEY")
    
    supabase: Client = create_client(url, key)

    offset = 0
    limit = 10
    # store_records  = []
    
    # try:
    while True:
    
        # store = supabase.table("store") \
        #                 .select("id","name","channel") \
        #                 .range(offset, offset + limit - 1) \
        #                 .not_.is_("name",'null') \
        #                 .execute()         
        store = supabase.rpc("get_store_data_pages", {
            "page_offset": offset,  # Your offset value
            "limit_count": limit    # Your limit value
        }).execute()
    
        print(f"Number of records stores read : {len(store.data)} + offset : {offset}")
        print(f"store read response : {store.data} ")
        if not store.data:
            break
        # Convert the array of records to a JSON string
        store_records_json = json.dumps(store.data)
        # Call the RPC function
        issues = supabase.rpc('get_issue_counts', {'in_values': json.loads(store_records_json)}).execute()
        print("Data:", issues.data)


        issues_records_json = json.dumps(issues.data)
        response = supabase.rpc('update_store_issues', {'issue_data': json.loads(issues_records_json)}).execute()

        update_response = supabase.rpc('update_total_counts', {'in_values': json.loads(store_records_json)}).execute()
        # store_records.extend(store.data)
        print("Data:", response.data)
        offset += limit
        # break

    # # Call the RPC function
    # response = supabase.rpc('getissuecounts', {
    #     # 'in_channel': store.data[0]['name'],
    #     # 'in_store_name': store.data[0]['channel']
    #     'in_channel': "SHOPRITE",
    #     'in_store_name': "ACORNHOEK MALL"
    # }).execute()

    # # Convert the array of records to a JSON string
    # store_records_json = json.dumps(store_records)
    # # Call the RPC function
    # response = supabase.rpc('get_issue_counts', {'in_values': json.loads(store_records_json)}).execute()

    # Handle the response
    # data = response.data

    # print("Data:", response)


    # print(f"Number of records store: {len(store_records)}")
    return {
        'statusCode': 200,
        'body': json.dumps({'message': 'success'})
    }
