"""
Runs after all task batches are inserted: update store issue counts,
invoke StartProcessQueue, send success notification.
Invoked by Step Functions Create Tasks workflow.
"""
import os
import json
from datetime import datetime
import boto3
from supabase import create_client, Client
from email_service import email_service

ssm = boto3.client('ssm')
lambda_client = boto3.client('lambda')

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

def send_success_notification():
    """Send success notification email."""
    try:
        email_service.send_notification(
            date=datetime.now().strftime('%Y-%m-%d'),
            status='success',
            error_message=f"Successfully processed imported tasks from SJREPORT\n\nTime: {datetime.now().isoformat()}",
            client_email=True,
            process_name='SJREPORT Import'
        )
        print("Success notification email sent")
    except Exception as e:
        print(f"Failed to send success notification email: {str(e)}")

def lambda_handler(event, context):
    """
    Event: { "week_start_date": str }
    """
    week_start_date = event.get('week_start_date')
    if not week_start_date:
        return {'statusCode': 400, 'error': 'week_start_date required'}

    url = get_parameter('/supabase/url')
    key = get_parameter('/supabase/anon')
    supabase: Client = create_client(url, key)

    # Update store issue counts
    try:
        supabase.rpc('update_store_issue_counts').execute()
        print("Store issue counts updated")
    except Exception as e:
        print(f"Error updating store issue counts: {str(e)}")
        # Continue to start queue and notify

    # Invoke StartProcessQueue (async)
    queue_arn = os.environ.get('START_PROCESS_QUEUE_ARN')
    if queue_arn:
        try:
            lambda_client.invoke(
                FunctionName=queue_arn,
                InvocationType='Event',
                Payload=json.dumps({'week_start_date': week_start_date})
            )
            print("StartProcessQueue invoked")
        except Exception as e:
            print(f"Error invoking StartProcessQueue: {str(e)}")

    send_success_notification()

    return {'statusCode': 200, 'message': 'Finalize completed', 'week_start_date': week_start_date}
