import json
from supabase import create_client, Client
import boto3
from email_service import email_service
import traceback
import os

# Initialize AWS SSM client
ssm = boto3.client('ssm')
LAMBDA_CLIENT = boto3.client('lambda')
BACKUP_SJREPORT_ARN = os.environ['BACKUP_SJREPORT_ARN']

def get_parameter(name):
    """Get a parameter from AWS SSM Parameter Store"""
    response = ssm.get_parameter(
        Name=name,
        WithDecryption=True
    )
    return response['Parameter']['Value']

def lambda_handler(event, context):
    try:
        # Initialize Supabase client 
        url: str = get_parameter('/supabase/url')
        key: str = get_parameter('/supabase/anon')
        
        supabase: Client = create_client(url, key)
        date = event['week_start_date']

        try:
            # Loop task customer-id updates in batches to avoid long single transactions
            BATCH_SIZE = 1000
            MAX_LOOPS = 200
            total_updated = 0
            loops = 0
            while True:
                loops += 1
                resp = supabase.rpc('update_task_customer_ids', {"p_batch_size": BATCH_SIZE, "p_hours_back": 1}).execute()
                updated = 0
                if hasattr(resp, "data"):
                    if isinstance(resp.data, int):
                        updated = resp.data
                    elif isinstance(resp.data, dict):
                        updated = resp.data.get("rows_updated", 0) or 0
                # Stop when there is no more work or the batch did less than requested
                if not updated or (isinstance(updated, int) and updated < BATCH_SIZE):
                    break
                total_updated += updated if isinstance(updated, int) else 0
                if loops >= MAX_LOOPS:
                    # Safety guard against infinite loops
                    break
        except Exception as e:
            # Notify but continue with the rest of the process
            email_service.send_notification(
                date=date,
                status='error',
                error_message=f"update_task_customer_ids failed: {str(e)}",
                client_email=False,
                process_name='Start Process Queue'
            )

        try:
            # run public.archive_old_tasks()
            supabase.rpc('archive_old_tasks').execute()
        except Exception as e:
            # Notify but continue with the rest of the process
            error_message = f"archive_old_tasks failed: {str(e)}\n\nStack Trace:\n{traceback.format_exc()}"
            email_service.send_notification(
                date=date,
                status='error',
                error_message=error_message,
                client_email=False,
                process_name='Start Process Queue - archive_old_tasks'
            )
            print(f"archive_old_tasks failed but continuing: {str(e)}")

        try:
            # Clear the existing queue before repopulating it.
            # NOTE: The Supabase Python client does not support `.truncate()` on tables,
            # so we delete all rows using a "match all" filter instead.
            # `neq('id', 0)` matches every row (assuming no row has id 0) which effectively
            # clears the table while still satisfying PostgREST's requirement for a filter.
            supabase.table('store_processing_queue').delete().neq('id', 0).execute()

            # Call the RPC function to repopulate the queue
            supabase.rpc('populate_store_process_queue').execute()
        except Exception as e:
            # Notify but continue with the rest of the process
            error_message = f"populate_store_process_queue failed: {str(e)}\n\nStack Trace:\n{traceback.format_exc()}"
            email_service.send_notification(
                date=date,
                status='error',
                error_message=error_message,
                client_email=False,
                process_name='Start Process Queue - populate_store_process_queue'
            )
            print(f"populate_store_process_queue failed but continuing: {str(e)}")

        # Invoke backup_sjreport Lambda function
        payload = json.dumps(event)
        response = LAMBDA_CLIENT.invoke(
            FunctionName=BACKUP_SJREPORT_ARN,
            InvocationType='Event',  # Asynchronous invocation
            Payload=payload
        )

        # Send success email
        email_id = email_service.send_notification(
            date=date,
            status='success',
            client_email=False,
            process_name='Added products to queue'
        )
        
        return {
            'statusCode': 200,
            'body': json.dumps({
                'message': 'success',
                'email_id': email_id
            })
        }
        
    except Exception as e:
        error_message = f"Error Type: {type(e).__name__}\nError Message: {str(e)}\n\nStack Trace:\n{traceback.format_exc()}"
        # Send error email
        email_id = email_service.send_notification(
            date=event.get('week_start_date', 'unknown'),
            status='error',
            error_message=error_message,
            client_email=False,
            process_name='Added products to queue'
        )
        
        return {
            'statusCode': 500,
            'body': json.dumps({
                'message': 'error',
                'error': str(e),
                'email_id': email_id
            })
        }
