Inspiration

Financial planning is slow and expensive. In Australia, a statement of advice will cost around $6,000 and can take months before the statement of advice is ready. Much of the time and delay is the result of twenty-year-old financial planning software that most advisers cannot use, and so rely on an (expensive) paraplanner who never meets the client. The adviser collects the data and sends it to the paraplanner, who wades through an ever-increasing pile. There had to be a better way. What if you included the software and paraplanner in the meeting in a way that wasn’t intrusive?

What it does

The app allows the adviser to ask the Alexa skill to do financial planning calculations using natural voice. For example, the adviser could simply say “test retirement,” and the skill will ask “what is the new contribution”, and then use this to update the client’s retirement situation, using a chart showing how long retirement funds will last with the old and new contributions, and how they measure up to life expectancy. The adviser has saved the cost of the paraplanner and planning software and dramatically reduced the time. A simple screen saver records the meeting for reference and compliance purposes.

How we built it

We used Lambda (version 20 using ES Modules), triggered by Alexa. The Lambda takes the Alexa input (JSON), does the calculation, and returns a JSON to Alexa, which renders the response. Lambda creates a chart and posts it to an S3 Bucket as a .png, which the Alexa APL accesses.

All details are stored in a DynamoDB database, so details can be used in future sessions.

Challenges we ran into

Lambda version 20 is not compatible with most chart programs we tried, and we wasted a lot of time sorting this out. We settled on Quick Chart, which isn’t that quick, and the process of sending a chart image to an S3 bucket and then to Alexa has a slight lag.

Accomplishments that we’re proud of

We have two Alexa Skills offering voice-based financial planning that are certified and live. These are offered in both our sites, www.finchat.com.au and www.smfp.au, which is probably why both sites have recently been nominated as finalists in the Australian Wealth Management’s Innovator of the Year.

What we learned

We learned AI can be very useful and found Claude very helpful and competent.

What’s next for Voice-based financial planning

This has enormous potential. Natural voice is the ultimate UI and not only helps advisers but can be used for general financial advice by ordinary people. It makes financial planning advice affordable and accessible. Adding APIs and accessing LLMs means users can get accurate answers as well as the knowledge curated by other service providers and IA services.

Lambda code

import * as Alexa from 'ask-sdk-core';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, UpdateCommand, ScanCommand } from '@aws-sdk/lib-dynamodb';
import { readFileSync } from "fs";
import path from "path";
import { fileURLToPath } from "url";
//import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { v4 as uuidv4 } from 'uuid';
import fs from 'fs/promises';
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";

// Add this S3 client initialization if missing:
const s3Client = new S3Client({ region: 'us-east-1' }); // or your region

// === Safe CommonJS import ===
import { createRequire } from "module";

const require = createRequire(import.meta.url);
const { SkillBuilders, getRequestType, getIntentName, getSupportedInterfaces } = require('ask-sdk-core');

// Initialize S3 client
const s3 = new S3Client({ region: "us-east-1" });

//LAUNCH START
const LaunchRequestHandler = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'LaunchRequest';
    },

    handle(handlerInput) {
        
        // Convert import.meta.url to __dirname equivalent
        const __filename = fileURLToPath(import.meta.url);
        const __dirname = path.dirname(__filename);
        
        // Read the JSON file
       // const menu = JSON.parse(readFileSync(path.join(__dirname, "menu.json"), "utf-8")); // THIS SHOWS BUTTONS
        const sfsStart = JSON.parse(readFileSync(path.join(__dirname, "sfsStart.json"), "utf-8"));
        
        function supportsAPL(handlerInput) {
            return (
                handlerInput.requestEnvelope.context?.System?.device?.supportedInterfaces?.["Alexa.Presentation.APL"]
            );
        }
        
        if (supportsAPL(handlerInput)) {
            handlerInput.responseBuilder.addDirective({
                type: "Alexa.Presentation.APL.RenderDocument",
                document: sfsStart,

                datasources: 
                {
                "retirementCalc": {
                     
                    "return1": [
                            {
                        "buttonStyle": "contained",
                        "vectorSource":"M12,0.5c-6.341,0-11.5,4.935-11.5,11s5.159,11,11.5,11c6.342,0,11.5-4.935,11.5-11S18.342,0.5,12,0.5z M15.833,16.083 c0,0.334-0.188,0.641-0.494,0.803C15.195,16.962,15.036,17,14.875,17c-0.178,0-0.353-0.047-0.507-0.139l-7.667-4.583 C6.42,12.109,6.25,11.817,6.25,11.5s0.17-0.609,0.451-0.778l7.667-4.583c0.296-0.177,0.668-0.188,0.972-0.025 c0.305,0.162,0.494,0.469,0.494,0.803V16.083L15.833,16.083z",
                        "buttonString": "<p> </p>"
                      }
                    ],
                        "stop1": [
                            {
                        "buttonStyle": "contained",
                        "vectorSource":"M1,0.314V23.5h21.5V0.314H1z M16.593,17.129H6.907V6.684h9.686V17.129z",
                        "buttonString": "<p> </p>"
                      }
                    ],
                        "home1": [
                            {
                        "buttonStyle": "contained",
                        "vectorSource":"M21.343,8.661l-7.895-7.105c-0.823-0.741-2.073-0.741-2.896,0L2.657,8.661C2.238,9.039,2,9.564,2,10.113V20c0,1.105,0.943,2,2.105,2H9v-9h6v9h4.895C21.057,22,22,21.105,22,20v-9.887C22,9.564,21.762,9.039,21.343,8.661z",
                        "buttonString": "<p> </p>"
                      }
                    ]
                }
                }           
            });
        }
    
        const speechText = 'Welcome to Adviser Assistant. The skill illustrates voice-based financial planning with the potential to revolutionise the industry. It focuses on the retirement module, which would be part of a suite of planning tools. Say, open retirement, to begin.';
        return handlerInput.responseBuilder
            .speak(speechText)
            .reprompt(speechText)
            .getResponse();
    }
    }

    //LAUNCH END

    ///******************RETIREMENT OVERVIEW ***********************************
const RetOverviewIntentHandler = {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        console.log('Full request:', JSON.stringify(request, null, 2));
         
        return (request.type === "IntentRequest" && request.intent.name === "retirementOverview") 
            || (request.type === "Alexa.Presentation.APL.UserEvent" && 
                request.arguments && 
                request.arguments.includes("retirement overview"));
    },
     async handle(handlerInput) {
        // Create DynamoDB Client
        const client = new DynamoDBClient({});
        const docClient = DynamoDBDocumentClient.from(client);
        
        try {
            const request = handlerInput.requestEnvelope.request;
            
            // Only extract slots if this is an IntentRequest
           let slots = {};
            if (request.type === "IntentRequest" && request.intent && request.intent.slots) {
                slots = request.intent.slots;
            }
            
            // Scan to retrieve all values
            const scanParams = {
                TableName: 'adviserAssist',
                Limit: 1
            };
            const scanCommand = new ScanCommand(scanParams);
            const response = await docClient.send(scanCommand);
            
            // Check if items exist
            if (!response.Items || response.Items.length === 0) {
                return handlerInput.responseBuilder
                    .speak('Sorry, no financial information was found.')
                    .getResponse();
            }
            
            // Extract current values in same order as function

            const item = response.Items[0];
            const currentUserBalance = item.attributes.userBalance || 0;
            const oldBalance = item.attributes.userBalance || 0;
            const beforetaxconts = item.attributes.userConts || 0;
            const rate = item.attributes.retireperformance || 0;
            const withdrawals = item.attributes.userWithdrawal || 0;
            const years = item.attributes.userTerm || 0;
            const yearsToRetire = item.attributes.userTerm || 0;
            const oldyrslasts = item.attributes.yrs || 0;
            const aftertaxconts = item.attributes.userContstwo || 0;
            const yrsLasts = item.attributes.yrs || 0;
            const newconts = item.attributes.testBeforeTax || 0;
            const oldFinalValue = item.attributes.Old_FV_total_2 || 0;

            let realgrowth = rate-3;

            const formattedoldFinalValue = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(oldFinalValue);

            const formattedNewConts1 = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(newconts);

            const formattedCurrentBalance = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(currentUserBalance);

            const formattedbeforetaxconts = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(beforetaxconts);

            const formattedaftertaxconts = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(aftertaxconts);

            const formattedwithdrawals = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(withdrawals);

            // Console logging for debugging
            console.log("current Balance $", formattedCurrentBalance);
            console.log("Before tax contributions $", formattedbeforetaxconts);
            console.log("New contributions $", formattedNewConts1);
            console.log("Real rate", realgrowth + "%");
            console.log("Withdrawals $", formattedwithdrawals);
            console.log("Years to retire", years);

         // const speechText = "<speak><break time='5s'/><voice name='Russell'>$15500</voice></speak>";
            const speechText = "<break time='5s'/>The clients retirement overview is displayed as a chart. The adviser can use this to explain options for a better outcome. Lets assume the adviser and client wish to examine increasing contributions. To do this the adviser simply says, test contributions. ";
            
            // Convert import.meta.url to __dirname equivalent
            const __filename = fileURLToPath(import.meta.url);
            const __dirname = path.dirname(__filename);

            // Read APL document using ES modules syntax
            const retirementOverview = JSON.parse(readFileSync(path.join(__dirname, "retirementOverview.json"), "utf-8"));

            function supportsAPL(handlerInput) {
                return (
                    handlerInput.requestEnvelope.context?.System?.device?.supportedInterfaces?.["Alexa.Presentation.APL"]
                );
            }

            if (supportsAPL(handlerInput)) {
                handlerInput.responseBuilder.addDirective({
                    type: "Alexa.Presentation.APL.RenderDocument",
                    document: retirementOverview,
                    datasources: {
                        "retirementCalc": {
                            "retireCalcData": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M23.775-0.5H11.978H0.18C-0.472-0.5-1,0.004-1,0.627v11.271v11.271c0,0.622,0.528,1.126,1.18,1.126h11.798 h11.798c0.651,0,1.18-0.504,1.18-1.126V0.627C24.955,0.004,24.427-0.5,23.775-0.5z M1.359,1.754h9.438v9.017H1.359V1.754z M1.359,13.024h9.438v9.018H1.359V13.024z M22.596,22.042h-9.438V11.897V1.754h9.438V22.042z M8.045,5.135H7.258V4.384c0-0.622-0.528-1.127-1.18-1.127c-0.651,0-1.18,0.505-1.18,1.127v0.751H4.112 c-0.651,0-1.18,0.504-1.18,1.127s0.528,1.127,1.18,1.127h0.787v0.751c0,0.623,0.528,1.127,1.18,1.127 c0.652,0,1.18-0.504,1.18-1.127V7.389h0.787c0.651,0,1.18-0.504,1.18-1.127S8.696,5.135,8.045,5.135z M8.045,16.406H4.112c-0.651,0-1.18,0.503-1.18,1.126c0,0.623,0.528,1.127,1.18,1.127h3.933 c0.651,0,1.18-0.504,1.18-1.127C9.225,16.91,8.696,16.406,8.045,16.406z M15.909,10.771h3.934c0.651,0,1.181-0.505,1.181-1.127c0-0.623-0.529-1.127-1.181-1.127h-3.934 c-0.65,0-1.179,0.505-1.179,1.127C14.73,10.266,15.259,10.771,15.909,10.771z M15.909,15.279h3.934c0.651,0,1.181-0.505,1.181-1.128c0-0.622-0.529-1.127-1.181-1.127h-3.934 c-0.65,0-1.179,0.505-1.179,1.127C14.73,14.774,15.259,15.279,15.909,15.279z",
                                    "buttonString": "<p>Retirement calculations</p>."
                                }
                            ],
                            "retireAssData": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M12.932,11.265c-1.33-0.533-1.715-0.856-1.715-1.438c0-0.466,0.353-1.01,1.348-1.01c0.88,0,1.556,0.347,1.562,0.35 c0.071,0.038,0.15,0.058,0.23,0.058c0.192,0,0.362-0.116,0.433-0.297l0.243-0.618c0.083-0.226-0.045-0.422-0.208-0.492 c-0.542-0.236-1.601-0.418-1.611-0.42c-0.018-0.003-0.077-0.016-0.077-0.085l-0.004-0.897c0-0.27-0.225-0.49-0.502-0.49h-0.433 c-0.277,0-0.502,0.22-0.502,0.49l0.001,0.943c0,0.072-0.079,0.103-0.107,0.11c-1.337,0.318-2.173,1.298-2.173,2.533 c0,1.54,1.273,2.236,2.648,2.759c1.099,0.432,1.547,0.869,1.547,1.51c0,0.698-0.635,1.186-1.544,1.186 c-0.777,0-1.828-0.492-1.838-0.497c-0.068-0.032-0.139-0.048-0.212-0.048c-0.2,0-0.375,0.121-0.444,0.309l-0.231,0.624 c-0.082,0.234,0.044,0.424,0.206,0.508c0.645,0.336,1.895,0.533,1.95,0.542c0.015,0.002,0.091,0.028,0.091,0.098v0.938 c0,0.27,0.226,0.491,0.502,0.491h0.448c0.278,0,0.502-0.221,0.502-0.491v-0.987c0-0.093,0.068-0.1,0.082-0.104 c1.425-0.32,2.303-1.362,2.303-2.67C15.427,12.824,14.68,11.956,12.932,11.265z M-2.973,29.5c-0.501,0-0.951-0.186-1.302-0.536l-0.188-0.188c-0.527-0.527-0.573-1.147-0.52-1.575 c0.079-0.624,0.417-1.263,0.953-1.799l6.203-6.203C2.542,18.829,2.507,18.317,2.317,18c-1.314-2.19-1.875-4.775-1.58-7.277 c0.304-2.577,1.458-4.931,3.335-6.809C6.275,1.712,9.207,0.5,12.329,0.5c3.123,0,6.055,1.212,8.258,3.414 c4.552,4.552,4.552,11.96,0,16.512c-2.202,2.201-5.095,3.415-8.143,3.415c0,0,0,0-0.001,0c-2.081-0.001-4.135-0.573-5.942-1.658 c-0.055-0.033-0.251-0.138-0.518-0.138c-0.262,0-0.502,0.102-0.694,0.294l-6.19,6.19C-1.518,29.146-2.273,29.5-2.973,29.5z M12.329,2.708c-2.531,0-4.908,0.983-6.694,2.769C3.85,7.262,2.867,9.639,2.867,12.171c0,2.531,0.983,4.908,2.769,6.694 c1.786,1.785,4.163,2.768,6.694,2.768s4.909-0.983,6.694-2.768c1.786-1.786,2.769-4.163,2.769-6.694 c0-2.532-0.982-4.909-2.769-6.694C17.238,3.691,14.861,2.708,12.329,2.708z",
                                    "buttonString": "<p>Retirement assumptions</p>."
                                }
                            ],
                            "retireTipsData": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M15.523,7.489C14.403,6.413,12.884,5.82,11.25,5.82S8.098,6.413,6.977,7.489c-1.168,1.121-1.812,2.684-1.812,4.4 c0,2.943,1.544,4.538,2.052,5.063c0.137,0.141,0.412,0.507,0.746,0.973c-0.245,0.245-0.396,0.575-0.396,0.941 c0,0.427,0.207,0.809,0.527,1.058c-0.03,0.103-0.048,0.211-0.048,0.325c0,0.409,0.211,0.769,0.532,0.989 c-0.051,0.122-0.08,0.275-0.08,0.415c0,0.591,0.496,1.094,1.105,1.094h3.292c0.609,0,1.105-0.503,1.105-1.094 c0-0.14-0.029-0.282-0.08-0.405c0.321-0.219,0.532-0.585,0.532-0.994c0-0.112-0.017-0.224-0.048-0.328 c0.321-0.25,0.527-0.631,0.527-1.06c0-0.357-0.146-0.682-0.379-0.926c0.347-0.48,0.633-0.858,0.773-1.004 c1.352-1.39,2.009-3.042,2.009-5.048C17.336,10.173,16.692,8.61,15.523,7.489z M11.25,10.585l2.021,2.907H12.22v4.043h-2.007 v-4.043H9.229L11.25,10.585z M11.216,4.084c0.658,0,1.205-0.566,1.205-1.264V0.764c0-0.699-0.547-1.264-1.205-1.264c-0.659,0-1.204,0.565-1.204,1.264 V2.82C10.012,3.518,10.558,4.084,11.216,4.084z M21.808,10.086h-1.94c-0.658,0-1.191,0.579-1.191,1.276c0,0.699,0.533,1.278,1.191,1.278h1.94 c0.658,0,1.192-0.579,1.192-1.278C23,10.666,22.466,10.086,21.808,10.086z M2.633,10.086h-1.94c-0.659,0-1.192,0.579-1.192,1.276c0,0.699,0.533,1.278,1.192,1.278h1.94 c0.658,0,1.192-0.579,1.192-1.278C3.825,10.666,3.291,10.086,2.633,10.086z M5.755,4.105L4.181,2.604C3.692,2.137,2.938,2.179,2.498,2.698C2.057,3.216,2.097,4.016,2.586,4.483l1.574,1.5 C4.387,6.2,4.673,6.307,4.957,6.307c0.326,0,0.651-0.141,0.886-0.418C6.284,5.371,6.244,4.572,5.755,4.105z M20.002,2.698c-0.44-0.519-1.194-0.561-1.684-0.094l-1.573,1.501c-0.489,0.467-0.528,1.266-0.089,1.784 c0.236,0.277,0.561,0.418,0.888,0.418c0.284,0,0.568-0.107,0.797-0.324l1.573-1.5C20.403,4.016,20.442,3.216,20.002,2.698z",
                                    "buttonString": "<p>Tips to boost retirement</p>."
                                }
                            ],
                            "return1": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M12,0.5c-6.341,0-11.5,4.935-11.5,11s5.159,11,11.5,11c6.342,0,11.5-4.935,11.5-11S18.342,0.5,12,0.5z M15.833,16.083 c0,0.334-0.188,0.641-0.494,0.803C15.195,16.962,15.036,17,14.875,17c-0.178,0-0.353-0.047-0.507-0.139l-7.667-4.583 C6.42,12.109,6.25,11.817,6.25,11.5s0.17-0.609,0.451-0.778l7.667-4.583c0.296-0.177,0.668-0.188,0.972-0.025 c0.305,0.162,0.494,0.469,0.494,0.803V16.083L15.833,16.083z",
                                    "buttonString": "<p> </p>"
                                }
                            ],
                            "stop1": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M1,0.314V23.5h21.5V0.314H1z M16.593,17.129H6.907V6.684h9.686V17.129z",
                                    "buttonString": "<p> </p>"
                                }
                            ],
                            "tick": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource":"M12.5-0.5C6.149-0.5,1,4.873,1,11.5c0,6.627,5.149,12,11.5,12S24,18.127,24,11.5C24,4.873,18.851-0.5,12.5-0.5zM10.857,16.747l-4.978-5.194l1.742-1.818l3.236,3.376l6.111-6.376l1.743,1.818L10.857,16.747z",
                                    "buttonString": "<p> </p>"
                                  }
                                ],
                                "update": [
                                    {
                                    "buttonStyle": "contained",
                                    "vectorSource":"M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z",
                                    "buttonString": "<p> Update </p>"
                                      }
                                    ],
                            "home1": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M23.775-0.5H11.978H0.18C-0.472-0.5-1,0.004-1,0.627v11.271v11.271c0,0.622,0.528,1.126,1.18,1.126h11.798h11.798c0.651,0,1.18-0.504,1.18-1.126V0.627C24.955,0.004,24.427-0.5,23.775-0.5zM1.359,1.754h9.438v9.017H1.359V1.754zM1.359,13.024h9.438v9.018H1.359V13.024zM22.596,22.042h-9.438V11.897V1.754h9.438V22.042zM8.045,5.135H7.258V4.384c0-0.622-0.528-1.127-1.18-1.127c-0.651,0-1.18,0.505-1.18,1.127v0.751H4.112c-0.651,0-1.18,0.504-1.18,1.127s0.528,1.127,1.18,1.127h0.787v0.751c0,0.623,0.528,1.127,1.18,1.127c0.652,0,1.18-0.504,1.18-1.127V7.389h0.787c0.651,0,1.18-0.504,1.18-1.127S8.696,5.135,8.045,5.135zM8.045,16.406H4.112c-0.651,0-1.18,0.503-1.18,1.126c0,0.623,0.528,1.127,1.18,1.127h3.933c0.651,0,1.18-0.504,1.18-1.127C9.225,16.91,8.696,16.406,8.045,16.406zM15.909,10.771h3.934c0.651,0,1.181-0.505,1.181-1.127c0-0.623-0.529-1.127-1.181-1.127h-3.934c-0.65,0-1.179,0.505-1.179,1.127C14.73,10.266,15.259,10.771,15.909,10.771zM15.909,15.279h3.934c0.651,0,1.181-0.505,1.181-1.128c0-0.622-0.529-1.127-1.181-1.127h-3.934c-0.65,0-1.179,0.505-1.179,1.127C14.73,14.774,15.259,15.279,15.909,15.279z",
                                    "buttonString": "<p> </p>"
                                }
                            ]
                        },
                        // Add your retirement data here for display in APL
                        myRetirementdata: {'message':formattedCurrentBalance},
                        myRetirementdata2: {'message':formattedbeforetaxconts},
                        myRetirementdata3: {'message':formattedNewConts1},
                        myRetirementdata4: {'message':realgrowth},
                        myRetirementdata5: {'message':formattedwithdrawals},
                        myRetirementdata6: {'message':yearsToRetire},
                        myRetirementdata7: {'message': yrsLasts},
                        myRetirementdata8: {'message': formattedoldFinalValue},
                    }
                });
            }
            
            return handlerInput.responseBuilder
                .speak(speechText)
                .getResponse();
                
        } catch (error) {
            // Comprehensive error logging
            console.error('Financial Update Error:', {
                message: error.message,
                name: error.name,
                stack: error.stack
            });
            
            return handlerInput.responseBuilder
                .speak('Sorry, there was an error processing your financial update.')
                .getResponse();
        }
    }
};

//export { RetOverviewIntentHandler };

//***********************END OVERVIEW RETIREMENT VALUES *****************************

///******************GET RETIREMENT VALUES ***********************************

const GetRetvaluesIntentHandler = {

    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        console.log('Full request:', JSON.stringify(request, null, 2));
        
        return (request.type === "IntentRequest" && request.intent.name === "GetRetvalues") 
            || (request.type === "Alexa.Presentation.APL.UserEvent" && 
                request.arguments && 
                request.arguments.includes("get retirement values"));
    },
    
    async handle(handlerInput) {
        // Create DynamoDB Client
        const client = new DynamoDBClient({});
        const docClient = DynamoDBDocumentClient.from(client);
        
        try {
            // Extract slots
            const request = handlerInput.requestEnvelope.request;
            
            // Only extract slots if this is an IntentRequest
            let slots = {};
            if (request.type === "IntentRequest" && request.intent && request.intent.slots) {
                slots = request.intent.slots;
            }
            
            // Scan to retrieve all values
            const scanParams = {
                TableName: 'adviserAssist',
                Limit: 1
            };
            const scanCommand = new ScanCommand(scanParams);
            const response = await docClient.send(scanCommand);
            
            // Check if items exist
            if (!response.Items || response.Items.length === 0) {
                return handlerInput.responseBuilder
                    .speak('Sorry, no financial information was found.')
                    .getResponse();
            }
            
            // Extract current values
            const item = response.Items[0];
            const currentUserBalance = item.attributes.userBalance || 0;
            const oldBalance = item.attributes.userBalance || 0;
            const beforetaxconts = item.attributes.userConts || 0;
            const rate = item.attributes.retireperformance || 0;
            const withdrawals = item.attributes.userWithdrawal || 0;
            const years = item.attributes.userTerm || 0;
            const yearsToRetire = item.attributes.userTerm || 0;
            const oldyrslasts = item.attributes.yrs || 0;
            const aftertaxconts = item.attributes.userContstwo || 0;

            const formattedCurrentBalance = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(currentUserBalance);

            const formattedbeforetaxconts = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(beforetaxconts);

            const formattedaftertaxconts = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(aftertaxconts);

            const formattedwithdrawals = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(withdrawals);

            // Console logging for debugging
            console.log("current Balance $", formattedCurrentBalance);
            console.log("Before tax contributions $", formattedbeforetaxconts);
            console.log("After tax contributions $", formattedaftertaxconts);
            console.log("Growth rate", rate + "%");
            console.log("Withdrawals $", formattedwithdrawals);
            console.log("Years to retire", years);

            const speechText = "These are displayed with their current values. Lets assume the adviser wants to show the client the benefits of increasing contributions. This is done by saying, test contributions'.";

            // Convert import.meta.url to __dirname equivalent
            const __filename = fileURLToPath(import.meta.url);
            const __dirname = path.dirname(__filename);

            // Read APL document using ES modules syntax
            const getRetValues = JSON.parse(readFileSync(path.join(__dirname, "getRetValues.json"), "utf-8"));

            function supportsAPL(handlerInput) {
                return (
                    handlerInput.requestEnvelope.context?.System?.device?.supportedInterfaces?.["Alexa.Presentation.APL"]
                );
            }

            if (supportsAPL(handlerInput)) {
                handlerInput.responseBuilder.addDirective({
                    type: "Alexa.Presentation.APL.RenderDocument",
                    document: getRetValues,
                    datasources: {
                        "retirementCalc": {
                            "retireCalcData": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M23.775-0.5H11.978H0.18C-0.472-0.5-1,0.004-1,0.627v11.271v11.271c0,0.622,0.528,1.126,1.18,1.126h11.798 h11.798c0.651,0,1.18-0.504,1.18-1.126V0.627C24.955,0.004,24.427-0.5,23.775-0.5z M1.359,1.754h9.438v9.017H1.359V1.754z M1.359,13.024h9.438v9.018H1.359V13.024z M22.596,22.042h-9.438V11.897V1.754h9.438V22.042z M8.045,5.135H7.258V4.384c0-0.622-0.528-1.127-1.18-1.127c-0.651,0-1.18,0.505-1.18,1.127v0.751H4.112 c-0.651,0-1.18,0.504-1.18,1.127s0.528,1.127,1.18,1.127h0.787v0.751c0,0.623,0.528,1.127,1.18,1.127 c0.652,0,1.18-0.504,1.18-1.127V7.389h0.787c0.651,0,1.18-0.504,1.18-1.127S8.696,5.135,8.045,5.135z M8.045,16.406H4.112c-0.651,0-1.18,0.503-1.18,1.126c0,0.623,0.528,1.127,1.18,1.127h3.933 c0.651,0,1.18-0.504,1.18-1.127C9.225,16.91,8.696,16.406,8.045,16.406z M15.909,10.771h3.934c0.651,0,1.181-0.505,1.181-1.127c0-0.623-0.529-1.127-1.181-1.127h-3.934 c-0.65,0-1.179,0.505-1.179,1.127C14.73,10.266,15.259,10.771,15.909,10.771z M15.909,15.279h3.934c0.651,0,1.181-0.505,1.181-1.128c0-0.622-0.529-1.127-1.181-1.127h-3.934 c-0.65,0-1.179,0.505-1.179,1.127C14.73,14.774,15.259,15.279,15.909,15.279z",
                                    "buttonString": "<p>Retirement calculations</p>."
                                }
                            ],
                            "retireAssData": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M12.932,11.265c-1.33-0.533-1.715-0.856-1.715-1.438c0-0.466,0.353-1.01,1.348-1.01c0.88,0,1.556,0.347,1.562,0.35 c0.071,0.038,0.15,0.058,0.23,0.058c0.192,0,0.362-0.116,0.433-0.297l0.243-0.618c0.083-0.226-0.045-0.422-0.208-0.492 c-0.542-0.236-1.601-0.418-1.611-0.42c-0.018-0.003-0.077-0.016-0.077-0.085l-0.004-0.897c0-0.27-0.225-0.49-0.502-0.49h-0.433 c-0.277,0-0.502,0.22-0.502,0.49l0.001,0.943c0,0.072-0.079,0.103-0.107,0.11c-1.337,0.318-2.173,1.298-2.173,2.533 c0,1.54,1.273,2.236,2.648,2.759c1.099,0.432,1.547,0.869,1.547,1.51c0,0.698-0.635,1.186-1.544,1.186 c-0.777,0-1.828-0.492-1.838-0.497c-0.068-0.032-0.139-0.048-0.212-0.048c-0.2,0-0.375,0.121-0.444,0.309l-0.231,0.624 c-0.082,0.234,0.044,0.424,0.206,0.508c0.645,0.336,1.895,0.533,1.95,0.542c0.015,0.002,0.091,0.028,0.091,0.098v0.938 c0,0.27,0.226,0.491,0.502,0.491h0.448c0.278,0,0.502-0.221,0.502-0.491v-0.987c0-0.093,0.068-0.1,0.082-0.104 c1.425-0.32,2.303-1.362,2.303-2.67C15.427,12.824,14.68,11.956,12.932,11.265z M-2.973,29.5c-0.501,0-0.951-0.186-1.302-0.536l-0.188-0.188c-0.527-0.527-0.573-1.147-0.52-1.575 c0.079-0.624,0.417-1.263,0.953-1.799l6.203-6.203C2.542,18.829,2.507,18.317,2.317,18c-1.314-2.19-1.875-4.775-1.58-7.277 c0.304-2.577,1.458-4.931,3.335-6.809C6.275,1.712,9.207,0.5,12.329,0.5c3.123,0,6.055,1.212,8.258,3.414 c4.552,4.552,4.552,11.96,0,16.512c-2.202,2.201-5.095,3.415-8.143,3.415c0,0,0,0-0.001,0c-2.081-0.001-4.135-0.573-5.942-1.658 c-0.055-0.033-0.251-0.138-0.518-0.138c-0.262,0-0.502,0.102-0.694,0.294l-6.19,6.19C-1.518,29.146-2.273,29.5-2.973,29.5z M12.329,2.708c-2.531,0-4.908,0.983-6.694,2.769C3.85,7.262,2.867,9.639,2.867,12.171c0,2.531,0.983,4.908,2.769,6.694 c1.786,1.785,4.163,2.768,6.694,2.768s4.909-0.983,6.694-2.768c1.786-1.786,2.769-4.163,2.769-6.694 c0-2.532-0.982-4.909-2.769-6.694C17.238,3.691,14.861,2.708,12.329,2.708z",
                                    "buttonString": "<p>Retirement assumptions</p>."
                                }
                            ],
                            "retireTipsData": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M15.523,7.489C14.403,6.413,12.884,5.82,11.25,5.82S8.098,6.413,6.977,7.489c-1.168,1.121-1.812,2.684-1.812,4.4 c0,2.943,1.544,4.538,2.052,5.063c0.137,0.141,0.412,0.507,0.746,0.973c-0.245,0.245-0.396,0.575-0.396,0.941 c0,0.427,0.207,0.809,0.527,1.058c-0.03,0.103-0.048,0.211-0.048,0.325c0,0.409,0.211,0.769,0.532,0.989 c-0.051,0.122-0.08,0.275-0.08,0.415c0,0.591,0.496,1.094,1.105,1.094h3.292c0.609,0,1.105-0.503,1.105-1.094 c0-0.14-0.029-0.282-0.08-0.405c0.321-0.219,0.532-0.585,0.532-0.994c0-0.112-0.017-0.224-0.048-0.328 c0.321-0.25,0.527-0.631,0.527-1.06c0-0.357-0.146-0.682-0.379-0.926c0.347-0.48,0.633-0.858,0.773-1.004 c1.352-1.39,2.009-3.042,2.009-5.048C17.336,10.173,16.692,8.61,15.523,7.489z M11.25,10.585l2.021,2.907H12.22v4.043h-2.007 v-4.043H9.229L11.25,10.585z M11.216,4.084c0.658,0,1.205-0.566,1.205-1.264V0.764c0-0.699-0.547-1.264-1.205-1.264c-0.659,0-1.204,0.565-1.204,1.264 V2.82C10.012,3.518,10.558,4.084,11.216,4.084z M21.808,10.086h-1.94c-0.658,0-1.191,0.579-1.191,1.276c0,0.699,0.533,1.278,1.191,1.278h1.94 c0.658,0,1.192-0.579,1.192-1.278C23,10.666,22.466,10.086,21.808,10.086z M2.633,10.086h-1.94c-0.659,0-1.192,0.579-1.192,1.276c0,0.699,0.533,1.278,1.192,1.278h1.94 c0.658,0,1.192-0.579,1.192-1.278C3.825,10.666,3.291,10.086,2.633,10.086z M5.755,4.105L4.181,2.604C3.692,2.137,2.938,2.179,2.498,2.698C2.057,3.216,2.097,4.016,2.586,4.483l1.574,1.5 C4.387,6.2,4.673,6.307,4.957,6.307c0.326,0,0.651-0.141,0.886-0.418C6.284,5.371,6.244,4.572,5.755,4.105z M20.002,2.698c-0.44-0.519-1.194-0.561-1.684-0.094l-1.573,1.501c-0.489,0.467-0.528,1.266-0.089,1.784 c0.236,0.277,0.561,0.418,0.888,0.418c0.284,0,0.568-0.107,0.797-0.324l1.573-1.5C20.403,4.016,20.442,3.216,20.002,2.698z",
                                    "buttonString": "<p>Tips to boost retirement</p>."
                                }
                            ],
                            "return1": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M12,0.5c-6.341,0-11.5,4.935-11.5,11s5.159,11,11.5,11c6.342,0,11.5-4.935,11.5-11S18.342,0.5,12,0.5z M15.833,16.083 c0,0.334-0.188,0.641-0.494,0.803C15.195,16.962,15.036,17,14.875,17c-0.178,0-0.353-0.047-0.507-0.139l-7.667-4.583 C6.42,12.109,6.25,11.817,6.25,11.5s0.17-0.609,0.451-0.778l7.667-4.583c0.296-0.177,0.668-0.188,0.972-0.025 c0.305,0.162,0.494,0.469,0.494,0.803V16.083L15.833,16.083z",
                                    "buttonString": "<p> </p>"
                                }
                            ],
                            "stop1": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M1,0.314V23.5h21.5V0.314H1z M16.593,17.129H6.907V6.684h9.686V17.129z",
                                    "buttonString": "<p> </p>"
                                }
                            ],
                            "home1": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M23.775-0.5H11.978H0.18C-0.472-0.5-1,0.004-1,0.627v11.271v11.271c0,0.622,0.528,1.126,1.18,1.126h11.798h11.798c0.651,0,1.18-0.504,1.18-1.126V0.627C24.955,0.004,24.427-0.5,23.775-0.5zM1.359,1.754h9.438v9.017H1.359V1.754zM1.359,13.024h9.438v9.018H1.359V13.024zM22.596,22.042h-9.438V11.897V1.754h9.438V22.042zM8.045,5.135H7.258V4.384c0-0.622-0.528-1.127-1.18-1.127c-0.651,0-1.18,0.505-1.18,1.127v0.751H4.112c-0.651,0-1.18,0.504-1.18,1.127s0.528,1.127,1.18,1.127h0.787v0.751c0,0.623,0.528,1.127,1.18,1.127c0.652,0,1.18-0.504,1.18-1.127V7.389h0.787c0.651,0,1.18-0.504,1.18-1.127S8.696,5.135,8.045,5.135zM8.045,16.406H4.112c-0.651,0-1.18,0.503-1.18,1.126c0,0.623,0.528,1.127,1.18,1.127h3.933c0.651,0,1.18-0.504,1.18-1.127C9.225,16.91,8.696,16.406,8.045,16.406zM15.909,10.771h3.934c0.651,0,1.181-0.505,1.181-1.127c0-0.623-0.529-1.127-1.181-1.127h-3.934c-0.65,0-1.179,0.505-1.179,1.127C14.73,10.266,15.259,10.771,15.909,10.771zM15.909,15.279h3.934c0.651,0,1.181-0.505,1.181-1.128c0-0.622-0.529-1.127-1.181-1.127h-3.934c-0.65,0-1.179,0.505-1.179,1.127C14.73,14.774,15.259,15.279,15.909,15.279z",
                                    "buttonString": "<p> </p>"
                                }
                            ]
                        },
                        // Add your retirement data here for display in APL

                    myRetirementdata: {'message':formattedCurrentBalance},
                    myRetirementdata2: {'message':formattedbeforetaxconts},
                    myRetirementdata3: {'message':formattedaftertaxconts},
                    myRetirementdata4: {'message':rate},
                    myRetirementdata5: {'message':formattedwithdrawals},
                    myRetirementdata6: {'message':yearsToRetire},
                    myRetirementdata7: {'message': oldyrslasts},

                    }
                });
            }
            
            return handlerInput.responseBuilder
                .speak(speechText)
                .getResponse();
                
        } catch (error) {
            // Comprehensive error logging
            console.error('Financial Update Error:', {
                message: error.message,
                name: error.name,
                stack: error.stack
            });
            
            return handlerInput.responseBuilder
                .speak('Sorry, there was an error processing your financial update.')
                .getResponse();
        }
    }
};

//***********************END GET RETIREMENT VALUES *****************************

///******************RETIREMENT CALCS START ***********************************

const RetirmentCalcsIntentHandler = {

    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        console.log('Full request:', JSON.stringify(request, null, 2));
        
        return (request.type === "IntentRequest" && request.intent.name === "retirementCalcs") 
            || (request.type === "Alexa.Presentation.APL.UserEvent" && 
                request.arguments && 
                request.arguments.includes("retirement calcs"));
    },
    
    async handle(handlerInput) {
        // Create DynamoDB Client
        const client = new DynamoDBClient({});
        const docClient = DynamoDBDocumentClient.from(client);
        
        try {
            // Extract slots
            const request = handlerInput.requestEnvelope.request;
            
            // Only extract slots if this is an IntentRequest
            let slots = {};
            if (request.type === "IntentRequest" && request.intent && request.intent.slots) {
                slots = request.intent.slots;
            }
            //get calcs
            // Scan to retrieve all values
            const scanParams = {
                TableName: 'adviserAssist',
                Limit: 1
            };
            const scanCommand = new ScanCommand(scanParams);
            const response = await docClient.send(scanCommand);
            
            // Check if items exist
            if (!response.Items || response.Items.length === 0) {
                return handlerInput.responseBuilder
                    .speak('Sorry, no financial information was found.')
                    .getResponse();
            }
            
            // Extract current values
            const item = response.Items[0];
            const newBalance = item.attributes.FV_total_2 || 0;
            const oldBalance = item.attributes.Old_FV_total_2 || 0;
            const oldconts = item.attributes.userConts || 0;
            const rate = item.attributes.retireperformance || 0;
            const withdrawals = item.attributes.userWithdrawal || 0;
            const years = item.attributes.userTerm || 0;
            const yearsToRetire = item.attributes.userTerm || 0;
            const oldyrslasts = item.attributes.yrs2 || 0;
            const newyrslasts = item.attributes.yrs3 || 0;
            const updatedconts = item.attributes.testBeforeTax || 0;

            const realRate = rate -3;

            const formattednewBalance = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(newBalance);

            const formattedoldBalance = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(oldBalance);

            const formattedoldconts = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(oldconts);

            const formattedupdatedconts = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(updatedconts);

            const formattedwithdrawals = new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
                maximumFractionDigits: 0, 
                minimumFractionDigits: 0, 
            }).format(withdrawals);

            // Console logging for debugging
                console.log("new Balance $", formattednewBalance);
                console.log("old Balance $", formattedoldBalance);
                console.log("old contributions $", formattedoldconts);
                console.log("new conts $", formattedupdatedconts);
                console.log("Growth rate", rate + "%");
                console.log("Withdrawals $", formattedwithdrawals);
                console.log("Years to retire", years);

            const speechText = "This view has more details for the adviser to discuss with the client, should the adviser deem it necessary.";

            // Convert import.meta.url to __dirname equivalent
            const __filename = fileURLToPath(import.meta.url);
            const __dirname = path.dirname(__filename);

            // Read APL document using ES modules syntax
            const retirementCalcs = JSON.parse(readFileSync(path.join(__dirname, "retirementCalcs.json"), "utf-8"));

            function supportsAPL(handlerInput) {
                return (
                    handlerInput.requestEnvelope.context?.System?.device?.supportedInterfaces?.["Alexa.Presentation.APL"]
                );
            }

            if (supportsAPL(handlerInput)) {
                handlerInput.responseBuilder.addDirective({
                    type: "Alexa.Presentation.APL.RenderDocument",
                    document: retirementCalcs,
                    datasources: {
                        "retirementCalc": {
                            "retireCalcData": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M23.775-0.5H11.978H0.18C-0.472-0.5-1,0.004-1,0.627v11.271v11.271c0,0.622,0.528,1.126,1.18,1.126h11.798 h11.798c0.651,0,1.18-0.504,1.18-1.126V0.627C24.955,0.004,24.427-0.5,23.775-0.5z M1.359,1.754h9.438v9.017H1.359V1.754z M1.359,13.024h9.438v9.018H1.359V13.024z M22.596,22.042h-9.438V11.897V1.754h9.438V22.042z M8.045,5.135H7.258V4.384c0-0.622-0.528-1.127-1.18-1.127c-0.651,0-1.18,0.505-1.18,1.127v0.751H4.112 c-0.651,0-1.18,0.504-1.18,1.127s0.528,1.127,1.18,1.127h0.787v0.751c0,0.623,0.528,1.127,1.18,1.127 c0.652,0,1.18-0.504,1.18-1.127V7.389h0.787c0.651,0,1.18-0.504,1.18-1.127S8.696,5.135,8.045,5.135z M8.045,16.406H4.112c-0.651,0-1.18,0.503-1.18,1.126c0,0.623,0.528,1.127,1.18,1.127h3.933 c0.651,0,1.18-0.504,1.18-1.127C9.225,16.91,8.696,16.406,8.045,16.406z M15.909,10.771h3.934c0.651,0,1.181-0.505,1.181-1.127c0-0.623-0.529-1.127-1.181-1.127h-3.934 c-0.65,0-1.179,0.505-1.179,1.127C14.73,10.266,15.259,10.771,15.909,10.771z M15.909,15.279h3.934c0.651,0,1.181-0.505,1.181-1.128c0-0.622-0.529-1.127-1.181-1.127h-3.934 c-0.65,0-1.179,0.505-1.179,1.127C14.73,14.774,15.259,15.279,15.909,15.279z",
                                    "buttonString": "<p>Retirement calculations</p>."
                                }
                            ],
                            "retireAssData": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M12.932,11.265c-1.33-0.533-1.715-0.856-1.715-1.438c0-0.466,0.353-1.01,1.348-1.01c0.88,0,1.556,0.347,1.562,0.35 c0.071,0.038,0.15,0.058,0.23,0.058c0.192,0,0.362-0.116,0.433-0.297l0.243-0.618c0.083-0.226-0.045-0.422-0.208-0.492 c-0.542-0.236-1.601-0.418-1.611-0.42c-0.018-0.003-0.077-0.016-0.077-0.085l-0.004-0.897c0-0.27-0.225-0.49-0.502-0.49h-0.433 c-0.277,0-0.502,0.22-0.502,0.49l0.001,0.943c0,0.072-0.079,0.103-0.107,0.11c-1.337,0.318-2.173,1.298-2.173,2.533 c0,1.54,1.273,2.236,2.648,2.759c1.099,0.432,1.547,0.869,1.547,1.51c0,0.698-0.635,1.186-1.544,1.186 c-0.777,0-1.828-0.492-1.838-0.497c-0.068-0.032-0.139-0.048-0.212-0.048c-0.2,0-0.375,0.121-0.444,0.309l-0.231,0.624 c-0.082,0.234,0.044,0.424,0.206,0.508c0.645,0.336,1.895,0.533,1.95,0.542c0.015,0.002,0.091,0.028,0.091,0.098v0.938 c0,0.27,0.226,0.491,0.502,0.491h0.448c0.278,0,0.502-0.221,0.502-0.491v-0.987c0-0.093,0.068-0.1,0.082-0.104 c1.425-0.32,2.303-1.362,2.303-2.67C15.427,12.824,14.68,11.956,12.932,11.265z M-2.973,29.5c-0.501,0-0.951-0.186-1.302-0.536l-0.188-0.188c-0.527-0.527-0.573-1.147-0.52-1.575 c0.079-0.624,0.417-1.263,0.953-1.799l6.203-6.203C2.542,18.829,2.507,18.317,2.317,18c-1.314-2.19-1.875-4.775-1.58-7.277 c0.304-2.577,1.458-4.931,3.335-6.809C6.275,1.712,9.207,0.5,12.329,0.5c3.123,0,6.055,1.212,8.258,3.414 c4.552,4.552,4.552,11.96,0,16.512c-2.202,2.201-5.095,3.415-8.143,3.415c0,0,0,0-0.001,0c-2.081-0.001-4.135-0.573-5.942-1.658 c-0.055-0.033-0.251-0.138-0.518-0.138c-0.262,0-0.502,0.102-0.694,0.294l-6.19,6.19C-1.518,29.146-2.273,29.5-2.973,29.5z M12.329,2.708c-2.531,0-4.908,0.983-6.694,2.769C3.85,7.262,2.867,9.639,2.867,12.171c0,2.531,0.983,4.908,2.769,6.694 c1.786,1.785,4.163,2.768,6.694,2.768s4.909-0.983,6.694-2.768c1.786-1.786,2.769-4.163,2.769-6.694 c0-2.532-0.982-4.909-2.769-6.694C17.238,3.691,14.861,2.708,12.329,2.708z",
                                    "buttonString": "<p>Retirement assumptions</p>."
                                }
                            ],
                            "retireTipsData": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M15.523,7.489C14.403,6.413,12.884,5.82,11.25,5.82S8.098,6.413,6.977,7.489c-1.168,1.121-1.812,2.684-1.812,4.4 c0,2.943,1.544,4.538,2.052,5.063c0.137,0.141,0.412,0.507,0.746,0.973c-0.245,0.245-0.396,0.575-0.396,0.941 c0,0.427,0.207,0.809,0.527,1.058c-0.03,0.103-0.048,0.211-0.048,0.325c0,0.409,0.211,0.769,0.532,0.989 c-0.051,0.122-0.08,0.275-0.08,0.415c0,0.591,0.496,1.094,1.105,1.094h3.292c0.609,0,1.105-0.503,1.105-1.094 c0-0.14-0.029-0.282-0.08-0.405c0.321-0.219,0.532-0.585,0.532-0.994c0-0.112-0.017-0.224-0.048-0.328 c0.321-0.25,0.527-0.631,0.527-1.06c0-0.357-0.146-0.682-0.379-0.926c0.347-0.48,0.633-0.858,0.773-1.004 c1.352-1.39,2.009-3.042,2.009-5.048C17.336,10.173,16.692,8.61,15.523,7.489z M11.25,10.585l2.021,2.907H12.22v4.043h-2.007 v-4.043H9.229L11.25,10.585z M11.216,4.084c0.658,0,1.205-0.566,1.205-1.264V0.764c0-0.699-0.547-1.264-1.205-1.264c-0.659,0-1.204,0.565-1.204,1.264 V2.82C10.012,3.518,10.558,4.084,11.216,4.084z M21.808,10.086h-1.94c-0.658,0-1.191,0.579-1.191,1.276c0,0.699,0.533,1.278,1.191,1.278h1.94 c0.658,0,1.192-0.579,1.192-1.278C23,10.666,22.466,10.086,21.808,10.086z M2.633,10.086h-1.94c-0.659,0-1.192,0.579-1.192,1.276c0,0.699,0.533,1.278,1.192,1.278h1.94 c0.658,0,1.192-0.579,1.192-1.278C3.825,10.666,3.291,10.086,2.633,10.086z M5.755,4.105L4.181,2.604C3.692,2.137,2.938,2.179,2.498,2.698C2.057,3.216,2.097,4.016,2.586,4.483l1.574,1.5 C4.387,6.2,4.673,6.307,4.957,6.307c0.326,0,0.651-0.141,0.886-0.418C6.284,5.371,6.244,4.572,5.755,4.105z M20.002,2.698c-0.44-0.519-1.194-0.561-1.684-0.094l-1.573,1.501c-0.489,0.467-0.528,1.266-0.089,1.784 c0.236,0.277,0.561,0.418,0.888,0.418c0.284,0,0.568-0.107,0.797-0.324l1.573-1.5C20.403,4.016,20.442,3.216,20.002,2.698z",
                                    "buttonString": "<p>Tips to boost retirement</p>."
                                }
                            ],
                            "return1": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M12,0.5c-6.341,0-11.5,4.935-11.5,11s5.159,11,11.5,11c6.342,0,11.5-4.935,11.5-11S18.342,0.5,12,0.5z M15.833,16.083 c0,0.334-0.188,0.641-0.494,0.803C15.195,16.962,15.036,17,14.875,17c-0.178,0-0.353-0.047-0.507-0.139l-7.667-4.583 C6.42,12.109,6.25,11.817,6.25,11.5s0.17-0.609,0.451-0.778l7.667-4.583c0.296-0.177,0.668-0.188,0.972-0.025 c0.305,0.162,0.494,0.469,0.494,0.803V16.083L15.833,16.083z",
                                    "buttonString": "<p> </p>"
                                }
                            ],
                            "stop1": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M1,0.314V23.5h21.5V0.314H1z M16.593,17.129H6.907V6.684h9.686V17.129z",
                                    "buttonString": "<p> </p>"
                                }
                            ],
                            "tick": [
                                {
                            "buttonStyle": "contained",
                            "vectorSource":"M12.5-0.5C6.149-0.5,1,4.873,1,11.5c0,6.627,5.149,12,11.5,12S24,18.127,24,11.5C24,4.873,18.851-0.5,12.5-0.5zM10.857,16.747l-4.978-5.194l1.742-1.818l3.236,3.376l6.111-6.376l1.743,1.818L10.857,16.747z",
                            "buttonString": "<p>Confirm change </p>"
                          }
                        ],
                            "home1": [
                                {
                                    "buttonStyle": "contained",
                                    "vectorSource": "M23.775-0.5H11.978H0.18C-0.472-0.5-1,0.004-1,0.627v11.271v11.271c0,0.622,0.528,1.126,1.18,1.126h11.798h11.798c0.651,0,1.18-0.504,1.18-1.126V0.627C24.955,0.004,24.427-0.5,23.775-0.5zM1.359,1.754h9.438v9.017H1.359V1.754zM1.359,13.024h9.438v9.018H1.359V13.024zM22.596,22.042h-9.438V11.897V1.754h9.438V22.042zM8.045,5.135H7.258V4.384c0-0.622-0.528-1.127-1.18-1.127c-0.651,0-1.18,0.505-1.18,1.127v0.751H4.112c-0.651,0-1.18,0.504-1.18,1.127s0.528,1.127,1.18,1.127h0.787v0.751c0,0.623,0.528,1.127,1.18,1.127c0.652,0,1.18-0.504,1.18-1.127V7.389h0.787c0.651,0,1.18-0.504,1.18-1.127S8.696,5.135,8.045,5.135zM8.045,16.406H4.112c-0.651,0-1.18,0.503-1.18,1.126c0,0.623,0.528,1.127,1.18,1.127h3.933c0.651,0,1.18-0.504,1.18-1.127C9.225,16.91,8.696,16.406,8.045,16.406zM15.909,10.771h3.934c0.651,0,1.181-0.505,1.181-1.127c0-0.623-0.529-1.127-1.181-1.127h-3.934c-0.65,0-1.179,0.505-1.179,1.127C14.73,10.266,15.259,10.771,15.909,10.771zM15.909,15.279h3.934c0.651,0,1.181-0.505,1.181-1.128c0-0.622-0.529-1.127-1.181-1.127h-3.934c-0.65,0-1.179,0.505-1.179,1.127C14.73,14.774,15.259,15.279,15.909,15.279z",
                                    "buttonString": "<p> </p>"
                                }
                            ]
                        },
                        // Add your retirement data here for display in APL

                    myRetirementdata: {'message':formattednewBalance},
                    myRetirementdata2: {'message':formattedoldBalance},
                    myRetirementdata9: {'message':formattedoldconts},
                    myRetirementdata3: {'message':formattedupdatedconts},
                    myRetirementdata4: {'message':rate},
                    myRetirementdata8: {'message':realRate},
                    myRetirementdata5: {'message':formattedwithdrawals},
                    myRetirementdata6: {'message':yearsToRetire},
                    myRetirementdata7: {'message': oldyrslasts},

                    }
                });
            }
            
            return handlerInput.responseBuilder
                .speak(speechText)
                .getResponse();
                
        } catch (error) {
            // Comprehensive error logging
            console.error('Financial Update Error:', {
                message: error.message,
                name: error.name,
                stack: error.stack
            });
            
            return handlerInput.responseBuilder
                .speak('Sorry, there was an error processing your financial update.')
                .getResponse();
        }
    }
};

//***********************END RETIREMENT CALCS *****************************


//###################### TEST BEFORE TAX WITH ASYNC CHART ###########################

const testNewBeforeTax = (userBalance, userConts, userContstwo, retireperformance, userWithdrawal, userTerm, yrs, userAge, testBeforeTax) => {
    console.log('=== RIGHT AT THE VERY BEGINNING TEST ==='); // Doesnt show

    let currentUserBalance = userBalance;
    let beforetaxconts = (userConts * 1);
    let Old_beforetaxconts = (userConts * 1);
    let aftertaxconts = userContstwo;
    let aftertaxconts3 = userContstwo;
    let Old_aftertaxconts = userContstwo;
    let rate = retireperformance / 100;
    let withdrawals = userWithdrawal;
    let withdrawal2 = userWithdrawal;
    let withdrawal3 = userWithdrawal;
    let Old_withdrawal3 = userWithdrawal;
    let yearsToRetire = userTerm;
    let oldyrslasts = yrs;
    let currentAge = userAge;
    //let newConts = slotBeforeTax;
    let newConts = testBeforeTax;

    console.log('=== ASSIGNMENT TO newConts ===');
    console.log('newConts value:', newConts);
    console.log('testBeforeTax value:', testBeforeTax);

    let inflation = 3 / 100;
    let annualRate = rate / 100;
    let realrate = rate - inflation;
    let FV_contrib1 = 10;
    let FV_contrib2 = 10;
    let FV_contrib3 = 10;
    let Old_FV_contrib1 = 10;
    let Old_FV_contrib2 = 10;
    let Old_FV_contrib3 = 10;

    let lifeExpectancy = 84 - yearsToRetire - currentAge; //19 years

console.log('=== DEBUGGING FV_contrib3 ===');

    let FV_balance = currentUserBalance * Math.pow(1 + realrate, yearsToRetire);
    let Old_FV_balance = currentUserBalance * Math.pow(1 + realrate, yearsToRetire);
    
    if(realrate == inflation){
        FV_contrib1 = beforetaxconts * ((Math.pow(1 + realrate, yearsToRetire) - 1) / realrate);   
        FV_contrib2 = aftertaxconts * ((Math.pow(1 + realrate, yearsToRetire) - 1) / realrate); 
        FV_contrib3 = (newConts) * ((Math.pow(1 + realrate, yearsToRetire) - 1) / realrate);   
        }
    else{
        FV_contrib1 = beforetaxconts * ((Math.pow(1 + realrate, yearsToRetire) - 1) / realrate);
        FV_contrib2 = aftertaxconts * ((Math.pow(1 + realrate, yearsToRetire) - 1) / realrate);  
        FV_contrib3 = (newConts) * ((Math.pow(1 + realrate, yearsToRetire) - 1) / realrate);  
    }

    if(realrate == inflation){
        Old_FV_contrib1 = beforetaxconts * ((Math.pow(1 + realrate, yearsToRetire) - 1) / realrate);   
        Old_FV_contrib2 = aftertaxconts * ((Math.pow(1 + realrate, yearsToRetire) - 1) / realrate); 

    }
    else{
        Old_FV_contrib1 = beforetaxconts * ((Math.pow(1 + realrate, yearsToRetire) - 1) / realrate); 
        Old_FV_contrib2 = aftertaxconts * ((Math.pow(1 + realrate, yearsToRetire) - 1) / realrate);  

    }

    // Total Future Value with new cont
    let FV_total = FV_balance + FV_contrib3 + FV_contrib2; //With the new conts
    let FV_total_2 = FV_balance + FV_contrib3 + FV_contrib2; //With the new conts

    // Old_Total Future Value with old cont
    let Old_FV_total = Old_FV_balance + Old_FV_contrib1 + Old_FV_contrib2;
    let Old_FV_total_2 = Old_FV_balance + Old_FV_contrib1 + Old_FV_contrib2;

    //console.log('FINAL VALUES);
    console.log('newConts:vvvvvvvvvvvvvvvv', newConts); //19999
    console.log('Old_beforetaxconts:vvvvvvvvvvvvvvvv', Old_beforetaxconts); //16666
    console.log('beforetaxconts:vvvvvvvvvvvvvvvv', beforetaxconts); //16666
    console.log('realrate:vvvvvvvvvvvvvvvv', realrate); //.04
    console.log('yearsToRetire:vvvvvvvvvvvvvvvv', yearsToRetire); //12
    console.log('realrate == inflation:vvvvvvvvvvvvvvvv', realrate == inflation); //False
    console.log('lifeExpectancy:vvvvvvvvvvvvvvvv', lifeExpectancy); //20
    console.log('beforetaxconts ************:', beforetaxconts); //16666
    console.log('FV_contrib3 newconts *************:', FV_contrib3); //300501
    console.log('FV_contrib2:aftertax**************', FV_contrib2); //0
    console.log('Old_FV_contrib1: beforetax************', Old_FV_contrib1); //250420
    console.log('Old_FV_contrib2:existing***********', Old_FV_contrib2);  //0
    console.log('FV_balance:*************', FV_balance);  //531880
    console.log('Old_FV_balance:*************',Old_FV_balance);  //531880
    console.log(' FV_total: ###################',  FV_total); //698831
    console.log('Old_FV_total:##################', Old_FV_total); //782300
 
    // Initialize Old_FV_total variables
    let Old_FV_total1 = 0;
    let Old_FV_total2 = 0;
    let Old_FV_total3 = 0;
    let Old_FV_total4 = 0;
    let Old_FV_total5 = 0;
    let Old_FV_total6 = 0;
    let Old_FV_total7 = 0;
    let Old_FV_total8 = 0;
    let Old_FV_total9 = 0;
    let Old_FV_total10 = 0;
    let Old_FV_total11 = 0;
    let Old_FV_total12 = 0;
    let Old_FV_total13 = 0;
    let Old_FV_total14 = 0;
    let Old_FV_total15 = 0;
    let Old_FV_total16 = 0;
    let Old_FV_total17 = 0;
    let Old_FV_total18 = 0;
    let Old_FV_total19 = 0;
    let Old_FV_total20 = 0;
    let Old_FV_total21 = 0;
    let Old_FV_total22 = 0;
    let Old_FV_total23 = 0;
    let Old_FV_total24 = 0;
    let Old_FV_total25 = 0;
    let Old_FV_total26 = 0;
    let Old_FV_total27 = 0;
    let Old_FV_total28 = 0;
    let Old_FV_total29 = 0;
    let Old_FV_total30 = 0;
    let Old_FV_total31 = 0;
    let Old_FV_total32 = 0;
    let Old_FV_total33 = 0;
    let Old_FV_total34 = 0;
    let Old_FV_total35 = 0;
    let Old_FV_total36 = 0;
    let Old_FV_total37 = 0;
    let Old_FV_total38 = 0;
    let Old_FV_total39 = 0;
    let Old_FV_total40 = 0;

    let FV_total1 = 0;
    let FV_total2 = 0;
    let FV_total3 = 0;
    let FV_total4 = 0;
    let FV_total5 = 0;
    let FV_total6 = 0;
    let FV_total7 = 0;
    let FV_total8 = 0;
    let FV_total9 = 0;
    let FV_total10 = 0;
    let FV_total11 = 0;
    let FV_total12 = 0;
    let FV_total13 = 0;
    let FV_total14 = 0;
    let FV_total15 = 0;
    let FV_total16 = 0;
    let FV_total17 = 0;
    let FV_total18 = 0;
    let FV_total19 = 0;
    let FV_total20 = 0;
    let FV_total21 = 0;
    let FV_total22 = 0;
    let FV_total23 = 0;
    let FV_total24 = 0;
    let FV_total25 = 0;
    let FV_total26 = 0;
    let FV_total27 = 0;
    let FV_total28 = 0;
    let FV_total29 = 0;
    let FV_total30 = 0;
    let FV_total31 = 0;
    let FV_total32 = 0;
    let FV_total33 = 0;
    let FV_total34 = 0;
    let FV_total35 = 0;
    let FV_total36 = 0;
    let FV_total37 = 0;
    let FV_total38 = 0;
    let FV_total39 = 0;
    let FV_total40 = 0;
    let FV_total41 = 0;

    // Output result - Future value deflated
    let yrs1 = 0;
    let yrs2 = 0;
    let yrs3 = 0;

    // GET yrs lasts
    while (yrs1 < 40) {
        FV_total = FV_total * (1 + realrate);
        Old_FV_total = Old_FV_total * (1 + realrate);
        FV_total = FV_total - withdrawal3;
        Old_FV_total = Old_FV_total - Old_withdrawal3;

        // Capture FV_total at specific years

         // Set to 0 if negative, but DON'T return early
        if(FV_total < 0){
            FV_total = 0; 
        }

        if(Old_FV_total < 0){
            Old_FV_total = 0; 
        }
       
        if (yrs1 == 0) {
            FV_total1 = FV_total; 
            Old_FV_total1 = Old_FV_total; 
            console.log("FV_total111111111",FV_total1);//666785
            console.log("Old_FV_total11111111",Old_FV_total1)//753592
            console.log("yrs2",yrs2);//486267
            console.log("yrs3",yrs3)//591881
        }
        if (yrs1 == 1) {
           FV_total2 = FV_total;
           Old_FV_total2 = Old_FV_total;
           if(FV_total1>0 && FV_total2 <1)
           {yrs2 = 2};
           if(Old_FV_total1>0 && Old_FV_total2 <1)
           {yrs3 = 2};
           console.log("yrs2",yrs2);//486267
           console.log("yrs3",yrs3)//591881

        }
        if (yrs1 == 2) {
            FV_total3 = FV_total;
            Old_FV_total3 = Old_FV_total;
            if(FV_total2>0 && FV_total3 <1)
            {yrs2 = 3};
            if(Old_FV_total2>0 && Old_FV_total3 <1)
            {yrs3 = 3};
            console.log("yrs2",yrs2);//486267
            console.log("yrs3",yrs3)//591881
         }
        if (yrs1 == 3) {
            FV_total4 = FV_total;
           Old_FV_total4 = Old_FV_total;
           if(FV_total3>0 && FV_total4 <1)
           {yrs2 = 4};
           if(Old_FV_total3>0 && Old_FV_total4 <1)
           {yrs3 = 4};
           console.log("FV_total4",FV_total4);//486267
           console.log("Old_FV_total4",Old_FV_total4)//591881
           console.log("yrs2",yrs2);//486267
           console.log("yrs3",yrs3)//591881
        }
        if (yrs1 == 4) {
            FV_total5 = FV_total;
           Old_FV_total5 = Old_FV_total;
           if(FV_total4>0 && FV_total5 <1)
           {yrs2 = 5};
           if(Old_FV_total4>0 && Old_FV_total5 <1)
           {yrs3 = 5};
           console.log("FV_total5",FV_total5);//486267
           console.log("Old_FV_total5",Old_FV_total5)//591881
           console.log("yrs2",yrs2);//486267
           console.log("yrs3",yrs3)//591881
        }

        if (yrs1 == 5) {
            FV_total6 = FV_total;
           Old_FV_total6 = Old_FV_total;
           if(FV_total5>0 && FV_total6 <1)
           {yrs2 = 6};
           if(Old_FV_total5>0 && Old_FV_total6 <1)
           {yrs3 = 6};
           console.log("FV_total6",FV_total6);//486267
           console.log("Old_FV_total6",Old_FV_total6)//591881
           console.log("yrs2",yrs2);//486267
           console.log("yrs3",yrs3)//591881
        }
        if (yrs1 == 6) {
            FV_total7 = FV_total;
           Old_FV_total7 = Old_FV_total;
           if(FV_total6>0 && FV_total7 <1)
           {yrs2 = 7};
           if(Old_FV_total6>0 && Old_FV_total7 <1)
           {yrs3 = 7};
           console.log("yrs2",yrs2);//486267
           console.log("yrs3",yrs3)//591881
        }
        if (yrs1 == 7) {
            FV_total8 = FV_total;
           Old_FV_total8 = Old_FV_total;
           if(FV_total7>0 && FV_total8 <1)
           {yrs2 = 8};
           if(Old_FV_total7>0 && Old_FV_total8 <1)
           {yrs3 = 8};
        }
        if (yrs1 == 8) {
            FV_total9 = FV_total;
           Old_FV_total9 = Old_FV_total;
           if(FV_total8>0 && FV_total9 <1)
           {yrs2 = 9};
           if(Old_FV_total8>0 && Old_FV_total9 <1)
           {yrs3 = 9};
        }
        if (yrs1 == 9) {
            FV_total10 = FV_total;
           Old_FV_total10 = Old_FV_total;
           if(FV_total9>0 && FV_total10 <1)
           {yrs2 = 10};
           if(Old_FV_total9>0 && Old_FV_total10 <1)
           {yrs3 = 10};
        }
        if (yrs1 == 10) {
            FV_total11 = FV_total;
           Old_FV_total11 = Old_FV_total;
           if(FV_total10>0 && FV_total11 <1)
           {yrs2 = 11};
           if(Old_FV_total10>0 && Old_FV_total11 <1)
           {yrs3 = 11};
        }
        if (yrs1 == 11) {
            FV_total12 = FV_total;
           Old_FV_total12 = Old_FV_total;
           if(FV_total1>0 && FV_total12 <1)
           {yrs2 = 12};
           if(Old_FV_total11>0 && Old_FV_total12 <1)
           {yrs3 = 12};
           console.log("yrs2",yrs2);//486267
           console.log("yrs3",yrs3)//591881
        }
        if (yrs1 == 12) {
            FV_total13 = FV_total;
           Old_FV_total13 = Old_FV_total;
           if(FV_total12>0 && FV_total13 <1)
           {yrs2 = 13};
           if(Old_FV_total12>0 && Old_FV_total13 <1)
           {yrs3 = 13};
           console.log("yrs2",yrs2);//486267
           console.log("yrs3",yrs3)//591881
        }
        if (yrs1 == 13) {
            FV_total14 = FV_total;
           Old_FV_total14 = Old_FV_total;
           if(FV_total13>0 && FV_total14 <1)
           {yrs2 = 14};
           if(Old_FV_total13>0 && Old_FV_total14 <1)
           {yrs3 = 14};
           console.log("yrs2",yrs2);//486267
           console.log("yrs3",yrs3)//591881
        }
        if (yrs1 == 14) {
            FV_total15 = FV_total;
           Old_FV_total15 = Old_FV_total;
           if(FV_total14>0 && FV_total15 <1)
           {yrs2 = 15};
           if(Old_FV_total14>0 && Old_FV_total15 <1)
           {yrs3 = 15};
           console.log("yrs2",yrs2);//486267
           console.log("yrs3",yrs3)//591881
        }
        if (yrs1 == 15) {
            FV_total16 = FV_total;
           Old_FV_total16 = Old_FV_total;
           if(FV_total15>0 && FV_total16 <1)
           {yrs2 = 16};
           if(Old_FV_total15>0 && Old_FV_total15 <1)
           {yrs3 = 16};
        }
        if (yrs1 == 16) {
            FV_total17 = FV_total;
           Old_FV_total17 = Old_FV_total;
           if(FV_total16>0 && FV_total17 <1)
           {yrs2 = 17};
           if(Old_FV_total16>0 && Old_FV_total17 <1)
           {yrs3 = 17};
        }
        if (yrs1 == 17) {
            FV_total18 = FV_total;
           Old_FV_total18 = Old_FV_total;
           if(FV_total17>0 && FV_total18 <1)
           {yrs2 = 18};
           if(Old_FV_total17>0 && Old_FV_total18 <1)
           {yrs3 = 18};
        }
        if (yrs1 == 18) {
            FV_total19 = FV_total;
           Old_FV_total19 = Old_FV_total;
           if(FV_total18>0 && FV_total19 <1)
           {yrs2 = 19};
           if(Old_FV_total18>0 && Old_FV_total19 <1)
           {yrs3 = 19};
        }
        if (yrs1 == 19) {
            FV_total20 = FV_total;
           Old_FV_total20 = Old_FV_total;
           if(FV_total19>0 && FV_total20 <1)
           {yrs2 = 20};
           if(Old_FV_total19>0 && Old_FV_total20 <1)
           {yrs3 = 20};
        }
        if (yrs1 == 20) {
            FV_total21 = FV_total;
           Old_FV_total21 = Old_FV_total;
           if(FV_total20>0 && FV_total21 <1)
           {yrs2 = 21};
           if(Old_FV_total20>0 && Old_FV_total21 <1)
           {yrs3 = 21};
        }
        if (yrs1 == 21) {
            FV_total22 = FV_total;
           Old_FV_total22 = Old_FV_total;
           if(FV_total21>0 && FV_total22 <1)
           {yrs2 = 22};
           if(Old_FV_total21>0 && Old_FV_total22 <1)
           {yrs3 = 22};
           console.log("yrs2",yrs2);//486267
           console.log("yrs3",yrs3)//591881
        }
        if (yrs1 == 22) {
            FV_total23 = FV_total;
           Old_FV_total23 = Old_FV_total;
           if(FV_total22>0 && FV_total23 <1)
           {yrs2 = 23};
           if(Old_FV_total22>0 && Old_FV_total23 <1)
           {yrs3 = 23};
        }
        if (yrs1 == 23) {
            FV_total24 = FV_total;
           Old_FV_total24 = Old_FV_total;
           if(FV_total23>0 && FV_total24 <1)
           {yrs2 = 24};
           if(Old_FV_total23>0 && Old_FV_total24 <1)
           {yrs3 = 24};
        }
        if (yrs1 == 24) {
            FV_total25 = FV_total;
           Old_FV_total25 = Old_FV_total;
           if(FV_total24>0 && FV_total25 <1)
           {yrs2 = 25};
           if(Old_FV_total24>0 && Old_FV_total25 <1)
           {yrs3 = 25};
        }
        if (yrs1 == 25) {
            FV_total26 = FV_total;
           Old_FV_total26 = Old_FV_total;
           if(FV_total25>0 && FV_total26 <1)
           {yrs2 = 26};
           if(Old_FV_total26>0 && Old_FV_total27 <1)
           {yrs3 = 26};
        }
 
        if (yrs1 == 26) {
            FV_total27 = FV_total;
           Old_FV_total27 = Old_FV_total;
           if(FV_total27>0 && FV_total28 <1)
           {yrs2 = 27};
           if(Old_FV_total27>0 && Old_FV_total28 <1)
           {yrs3 = 27};
        }
        if (yrs1 == 27) {
            FV_total28 = FV_total;
           Old_FV_total28 = Old_FV_total;
           if(FV_total28>0 && FV_total29 <1)
           {yrs2 = 28};
           if(Old_FV_total28>0 && Old_FV_total29 <1)
           {yrs3 = 28};
        }
        if (yrs1 == 28) {
            FV_total29 = FV_total;
           Old_FV_total29 = Old_FV_total;
           if(FV_total29>0 && FV_total30 <1)
           {yrs2 = 29};
           if(Old_FV_total29>0 && Old_FV_total30 <1)
           {yrs3 = 29};
        }
        if (yrs1 == 29) {
            FV_total30 = FV_total;
           Old_FV_total30 = Old_FV_total;
           if(FV_total30>0 && FV_total31 <1)
           {yrs2 = 30};
           if(Old_FV_total30>0 && Old_FV_total31 <1)
           {yrs3 = 30};
           console.log("yrs2",yrs2);//486267
           console.log("yrs3",yrs3)//591881
        }
        if (yrs1 == 30) {
            FV_total31 = FV_total;
           Old_FV_total31 = Old_FV_total;
           if(FV_total31>0 && FV_total32 <1)
           {yrs2 = 31};
           if(Old_FV_total31>0 && Old_FV_total32 <1)
           {yrs3 = 31};
        }
        if (yrs1 == 31) {
            FV_total32 = FV_total;
           Old_FV_total32 = Old_FV_total;
           if(FV_total32>0 && FV_total33 <1)
           {yrs2 = 32};
           if(Old_FV_total32>0 && Old_FV_total33 <1)
           {yrs3 = 32};
        }
        if (yrs1 == 32) {
            FV_total33 = FV_total;
           Old_FV_total33 = Old_FV_total;
           if(FV_total33>0 && FV_total34 <1)
           {yrs2 = 33};
           if(Old_FV_total33>0 && Old_FV_total34 <1)
           {yrs3 = 33};
        }
        if (yrs1 == 33) {
            FV_total34 = FV_total;
           Old_FV_total34 = Old_FV_total;
           if(FV_total34>0 && FV_total35 <1)
           {yrs2 = 34};
           if(Old_FV_total34>0 && Old_FV_total35 <1)
           {yrs3 = 34};
        }
        if (yrs1 == 34) {
            FV_total35 = FV_total;
           Old_FV_total35 = Old_FV_total;
           if(FV_total35>0 && FV_total36 <1)
           {yrs2 = 35};
           if(Old_FV_total35>0 && Old_FV_total36 <1)
           {yrs3 = 35};
           console.log("yrs2",yrs2);//486267
           console.log("yrs3",yrs3)//591881
        }
        if (yrs1 == 35) {
            FV_total36 = FV_total;
           Old_FV_total36 = Old_FV_total;
           if(FV_total36>0 && FV_total37 <1)
           {yrs2 = 36};
           if(Old_FV_total36>0 && Old_FV_total37 <1)
           {yrs3 = 36};
        }
        if (yrs1 == 36) {
            FV_total37 = FV_total;
           Old_FV_total37 = Old_FV_total;
           if(FV_total37>0 && FV_total38 <1)
           {yrs2 = 36};
           if(Old_FV_total37>0 && Old_FV_total38 <1)
           {yrs3 = 36};
        }
        if (yrs1 == 37) {
            FV_total38 = FV_total;
           Old_FV_total38 = Old_FV_total;
           if(FV_total38>0 && FV_total39 <1)
           {yrs2 = 37};
           if(Old_FV_total38>0 && Old_FV_total39 <1)
           {yrs3 = 37};
           console.log("yrs2",yrs2);//486267
           console.log("yrs3",yrs3)//591881
        }
        if (yrs1 == 38) {
            FV_total39 = FV_total;
           Old_FV_total39 = Old_FV_total;
           if(FV_total39>0 && FV_total40 <1)
           {yrs2 = 38};
           if(Old_FV_total39>0 && Old_FV_total40 <1)
           {yrs3 = 38};
        }
        if (yrs1 == 39) {
            FV_total40 = FV_total;
           Old_FV_total40 = Old_FV_total;
           if(FV_total40>0 && FV_total41 <1)
           {yrs2 = 39};
           if(Old_FV_total40>0 && Old_FV_total41 <1)
           {yrs3 = 39};
        }
        console.log("FV_total",FV_total)

        if (withdrawal3 < 0) {
            withdrawal3 = 0;
        }
        
        if (Old_withdrawal3 < 0) {
            Old_withdrawal3 = 0;
        }
        
        if (yrs1 > 39) {
            return { yrs1: "over 40" };
        }
        
        yrs1++;
    }
    
    return {yrs1, yrs2, yrs3, lifeExpectancy,  FV_total_2, Old_FV_total_2, FV_total1, FV_total2, FV_total3, FV_total4, FV_total5, FV_total6, FV_total7, FV_total8, FV_total9, FV_total10, FV_total11, FV_total12, FV_total13, FV_total14, FV_total15, FV_total16, FV_total17, FV_total18, FV_total19, FV_total20,FV_total21, FV_total22, FV_total23, FV_total24, FV_total25, FV_total26, FV_total27, FV_total28, FV_total29, FV_total30, FV_total31, FV_total32, FV_total33, FV_total34, FV_total35, FV_total36, FV_total37, FV_total38, FV_total39, FV_total40, Old_FV_total1, Old_FV_total2, Old_FV_total3, Old_FV_total4, Old_FV_total5, Old_FV_total6, Old_FV_total7, Old_FV_total8, Old_FV_total9, Old_FV_total10, Old_FV_total11, Old_FV_total12, Old_FV_total13, Old_FV_total14, Old_FV_total15, Old_FV_total16, Old_FV_total17, Old_FV_total18, Old_FV_total19, Old_FV_total20,Old_FV_total21, Old_FV_total22, Old_FV_total23, Old_FV_total24, Old_FV_total25, Old_FV_total26, Old_FV_total27, Old_FV_total28, Old_FV_total29, Old_FV_total30, Old_FV_total31, Old_FV_total32, Old_FV_total33, Old_FV_total34, Old_FV_total35, Old_FV_total36, Old_FV_total37, Old_FV_total38, Old_FV_total39, Old_FV_total40};

};

//START CHART
async function generateTestChart(chartData) {
    console.log('=== CHART GENERATION START ===');
    console.log('Input chartData:', JSON.stringify(chartData, null, 2));
    
    try {
        const chartConfig = {
            type: 'line',
            data: {
                labels: chartData.labels || ['1', ' ', '3', ' ', '5', ' ','7', ' ', '9', ' ', '11', ' ','13', ' ', '15', ' ', '17', ' ','19', ' ', '21', ' ', '23', ' ','25', ' ', '27', ' ', '29', ' ','31', ' ', '33', ' ', '35', ' ','37', ' ', '39', ' '],
                datasets: [
                    {
                        label: chartData.label || 'Old contributions',
                        data: chartData.data || [],
                        borderColor: '#4a90e2', // Lighter blue
                        backgroundColor: 'rgba(74, 144, 226, 0.3)', // Less transparent
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        type: 'line'
                    },
                    {
                        label: chartData.label2 || 'New contributions',
                        data: chartData.data2 || [],
                        borderColor: '#2ecc71', // Brighter green
                        backgroundColor: 'rgba(46, 204, 113, 0.3)', // Less transparent
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        type: 'line'
                    },
                    {
                        label: chartData.chartLabel || 'Life expectancy',
                        data: chartData.barchartData || [],
                        borderWidth: 0, // Remove border completely
                        backgroundColor: 'rgba(255, 193, 0, 0.5)', // Lighter orange (was 0.7)
                        type: 'bar',
                        barPercentage: 0.4, // Make slimmer (was 0.8)
                        categoryPercentage: 0.6 // Adjust spacing (was 0.9)
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        labels: {
                            color: '#ffffff', // White legend text
                            font: {
                                size: 14
                            }
                        }
                    }
                },
               scales: {
                y: {
                    beginAtZero: true,
                    title: { 
                        display: true, 
                        text: 'Balance ($)', 
                        font: { size: 16 }, 
                        padding: { top: 10, bottom: 10 },
                        color: '#ffffff' // Changed from '#111111'
                    },
                    ticks: {
                        font: { size: 14 },
                        color: '#ffffff' // Changed from '#111111'
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)' // Light grid lines
                    }
                },
                x: {
                    title: { 
                        display: true, 
                        text: 'Years after retirement', 
                        font: { size: 16 }, 
                        padding: { top: 10, bottom: 10 },
                        color: '#ffffff' // Changed from '#111111'
                    },
                    ticks: {
                        font: { size: 14 },
                        color: '#ffffff' // Changed from '#111111'
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)' // Light grid lines
                    }
                }
            }
            }
        };

        console.log('Chart config created:', JSON.stringify(chartConfig, null, 2));

        // Generate chart using QuickChart API
        console.log('Making request to QuickChart API...');
        const response = await fetch('https://quickchart.io/chart', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                chart: chartConfig,
                width: 1000,
                height: 550,
                format: 'png',
                backgroundColor: '#0c3066',
                version: '3',
                // Add border styling
                devicePixelRatio: 2 // Higher quality
            })
        });

        console.log('QuickChart API response status:', response.status);

        if (!response.ok) {
            const errorText = await response.text();
            console.error('QuickChart API error response:', errorText);
            throw new Error(`Chart API failed: ${response.status} - ${errorText}`);
        }

        const chartBuffer = await response.arrayBuffer();
        console.log('Chart buffer size:', chartBuffer.byteLength, 'bytes');
        
        if (chartBuffer.byteLength === 0) {
            throw new Error('Received empty chart buffer from QuickChart API');
        }

        // Upload to S3 with fixed filename
        const fileName = 'peforeTax.png';
        console.log('Uploading to S3 with filename:', fileName);
        
        const uploadParams = {
            Bucket: 'finchat-charts',
            Key: fileName,
            Body: new Uint8Array(chartBuffer),
            ContentType: 'image/png',
        };

        const uploadResult = await s3Client.send(new PutObjectCommand(uploadParams));
        console.log('S3 upload result:', uploadResult);

        // Verify the file exists
        try {
            const headParams = {
                Bucket: 'finchat-charts',
                Key: fileName
            };
            const headResult = await s3Client.send(new HeadObjectCommand(headParams));
            console.log('S3 file verification successful:', {
                ContentLength: headResult.ContentLength,
                LastModified: headResult.LastModified
            });
        } catch (verifyError) {
            console.error('Failed to verify chart file in S3:', verifyError);
        }

        // Return filename with cache-busting parameter
        const cacheBuster = Date.now();
        const finalUrl = `${fileName}?v=${cacheBuster}`;
        console.log('Final chart URL:', `https://finchat-charts.s3.us-east-1.amazonaws.com/${finalUrl}`);
        
        console.log('=== CHART GENERATION SUCCESS ===');
        return finalUrl;
        
    } catch (error) {
        console.error('=== CHART GENERATION FAILED ===');
        console.error('Error details:', error);
        throw error;
    }
}

// Main Lambda handler 
// Add this function definition
async function generateTestChartAsync(calculationResult, userId) {
    console.log('=== HANDLER START ===');
    console.log('=== CHART GENERATION START ===');
    console.log('User ID:', userId);
    console.log('Calculation Result:', JSON.stringify(calculationResult, null, 2));
    
    try {
        // Create chart data from calculation results - FIXED DATA ASSIGNMENT
        const chartData = {
            title: 'Updating before tax contributions',
            label: 'Old contributions',
            data: [
                // OLD CONTRIBUTIONS DATA (was incorrectly using FV_total)
                Math.round(calculationResult.Old_FV_total1 || 0),
                Math.round(calculationResult.Old_FV_total2 || 0), 
                Math.round(calculationResult.Old_FV_total3 || 0),
                Math.round(calculationResult.Old_FV_total4 || 0),
                Math.round(calculationResult.Old_FV_total5 || 0),
                Math.round(calculationResult.Old_FV_total6 || 0),
                Math.round(calculationResult.Old_FV_total7 || 0), 
                Math.round(calculationResult.Old_FV_total8 || 0),
                Math.round(calculationResult.Old_FV_total9 || 0),
                Math.round(calculationResult.Old_FV_total10 || 0),
                Math.round(calculationResult.Old_FV_total11 || 0),
                Math.round(calculationResult.Old_FV_total12 || 0), 
                Math.round(calculationResult.Old_FV_total13 || 0),
                Math.round(calculationResult.Old_FV_total14 || 0),
                Math.round(calculationResult.Old_FV_total15 || 0),
                Math.round(calculationResult.Old_FV_total16 || 0),
                Math.round(calculationResult.Old_FV_total17 || 0), 
                Math.round(calculationResult.Old_FV_total18 || 0),
                Math.round(calculationResult.Old_FV_total19 || 0),
                Math.round(calculationResult.Old_FV_total20 || 0),
                Math.round(calculationResult.Old_FV_total21 || 0),
                Math.round(calculationResult.Old_FV_total22 || 0), 
                Math.round(calculationResult.Old_FV_total23 || 0),
                Math.round(calculationResult.Old_FV_total24 || 0),
                Math.round(calculationResult.Old_FV_total25 || 0),
                Math.round(calculationResult.Old_FV_total26 || 0),
                Math.round(calculationResult.Old_FV_total27 || 0), 
                Math.round(calculationResult.Old_FV_total28 || 0),
                Math.round(calculationResult.Old_FV_total29 || 0),
                Math.round(calculationResult.Old_FV_total30 || 0),
                Math.round(calculationResult.Old_FV_total31 || 0),
                Math.round(calculationResult.Old_FV_total32 || 0), 
                Math.round(calculationResult.Old_FV_total33 || 0),
                Math.round(calculationResult.Old_FV_total34 || 0),
                Math.round(calculationResult.Old_FV_total35 || 0),
                Math.round(calculationResult.Old_FV_total36 || 0),
                Math.round(calculationResult.Old_FV_total37 || 0), 
                Math.round(calculationResult.Old_FV_total38 || 0),
                Math.round(calculationResult.Old_FV_total39 || 0),
                Math.round(calculationResult.Old_FV_total40 || 0)
            ],
            label2: 'New contributions',
            data2: [
                // NEW CONTRIBUTIONS DATA (was incorrectly using Old_FV_total)
                Math.round(calculationResult.FV_total1 || 0),
                Math.round(calculationResult.FV_total2 || 0), 
                Math.round(calculationResult.FV_total3 || 0),
                Math.round(calculationResult.FV_total4 || 0),
                Math.round(calculationResult.FV_total5 || 0),
                Math.round(calculationResult.FV_total6 || 0),
                Math.round(calculationResult.FV_total7 || 0), 
                Math.round(calculationResult.FV_total8 || 0),
                Math.round(calculationResult.FV_total9 || 0),
                Math.round(calculationResult.FV_total10 || 0),
                Math.round(calculationResult.FV_total11 || 0),
                Math.round(calculationResult.FV_total12 || 0), 
                Math.round(calculationResult.FV_total13 || 0),
                Math.round(calculationResult.FV_total14 || 0),
                Math.round(calculationResult.FV_total15 || 0),
                Math.round(calculationResult.FV_total16 || 0),
                Math.round(calculationResult.FV_total17 || 0), 
                Math.round(calculationResult.FV_total18 || 0),
                Math.round(calculationResult.FV_total19 || 0),
                Math.round(calculationResult.FV_total20 || 0),
                Math.round(calculationResult.FV_total21 || 0),
                Math.round(calculationResult.FV_total22 || 0), 
                Math.round(calculationResult.FV_total23 || 0),
                Math.round(calculationResult.FV_total24 || 0),
                Math.round(calculationResult.FV_total25 || 0),
                Math.round(calculationResult.FV_total26 || 0),
                Math.round(calculationResult.FV_total27 || 0), 
                Math.round(calculationResult.FV_total28 || 0),
                Math.round(calculationResult.FV_total29 || 0),
                Math.round(calculationResult.FV_total30 || 0),
                Math.round(calculationResult.FV_total31 || 0),
                Math.round(calculationResult.FV_total32 || 0), 
                Math.round(calculationResult.FV_total33 || 0),
                Math.round(calculationResult.FV_total34 || 0),
                Math.round(calculationResult.FV_total35 || 0),
                Math.round(calculationResult.FV_total36 || 0),
                Math.round(calculationResult.FV_total37 || 0), 
                Math.round(calculationResult.FV_total38 || 0),
                Math.round(calculationResult.FV_total39 || 0),
                Math.round(calculationResult.FV_total40 || 0)
            ],
 
           barchartData: Array.from({length: 40}, (_, i) => 
           i === ((calculationResult.lifeExpectancy || 19) - 1) ? (calculationResult.FV_total1 || 0) : null
       ),

            labels: ['1', ' ', '3', ' ', '5', ' ','7', ' ', '9', ' ', '11', ' ','13', ' ', '15', ' ', '17', ' ','19', ' ', '21', ' ', '23', ' ','25', ' ', '27', ' ', '29', ' ','31', ' ', '33', ' ', '35', ' ','37', ' ', '39', ' ']
        };
        
        console.log('Chart data prepared:', JSON.stringify(chartData, null, 2));

    //END CHART
        
        // Call your existing generateChart function
        console.log('Calling generateChart function...');
        const fileName = await generateTestChart(chartData);
        
        console.log(`SUCCESS: Chart generated with filename: ${fileName}`);
        console.log('=== CHART GENERATION COMPLETE ===');
        return fileName;
        
    } catch (error) {
        console.error('=== CHART GENERATION FAILED ===');
        console.error('Error details:', error);
        console.error('Error stack:', error.stack);
        throw error;
    }
}
//testBeforeTax

export const chartTestHandler = async (event) => {
    console.log('Lambda invoked:', JSON.stringify(event, null, 2));
    
    try {
        // Handle Alexa skill requests
        if (event.request && event.request.type) {
            // This is an Alexa skill request
            
            if (event.request.type === 'IntentRequest') {
                const intentName = event.request.intent.name;
                
                if (intentName === 'GenerateTestChartIntent') {
                    console.log('Starting background chart generation...');
                    
                    // Generate chart in background
                    const fileName = await generateTestChart({
                        title: '111',
                        label: '222',
                        data: [lifeExpectancy, FV_total1, FV_total2, FV_total3, FV_total4, FV_total5, FV_total6, FV_total7, FV_total8, FV_total9, FV_total10, FV_total11, FV_total12, FV_total13, FV_total14, FV_total15, FV_total16, FV_total17, FV_total18, FV_total19, FV_total20,FV_total21, FV_total22, FV_total23, FV_total24, FV_total25, FV_total26, FV_total27, FV_total28, FV_total29, FV_total30, FV_total31, FV_total32, FV_total33, FV_total34, FV_total35, FV_total36, FV_total37, FV_total38, FV_total39, FV_total40],
                        
                        data2: [lifeExpectancy, Old_FV_total1, Old_FV_total2, Old_FV_total3, Old_FV_total4, Old_FV_total5, Old_FV_total6, Old_FV_total7, Old_FV_total8, Old_FV_total9, Old_FV_total10, Old_FV_total11, Old_FV_total12, Old_FV_total13, Old_FV_total14, Old_FV_total15, Old_FV_total16, Old_FV_total17, Old_FV_total18, Old_FV_total19, Old_FV_total20,Old_FV_total21, Old_FV_total22, Old_FV_total23, Old_FV_total24, Old_FV_total25, Old_FV_total26, Old_FV_total27, Old_FV_total28, Old_FV_total29, Old_FV_total30, Old_FV_total31, Old_FV_total32, Old_FV_total33, Old_FV_total34, Old_FV_total35, Old_FV_total36, Old_FV_total37, Old_FV_total38, Old_FV_total39, Old_FV_total40],

                        data3: [lifeExpectancy],

                        labels: ['1', ' ', '3', ' ', '5', ' ','7', ' ', '9', ' ', '11', ' ','13', ' ', '15', ' ', '17', ' ','19', ' ', '21', ' ', '23', ' ','25', ' ', '27', ' ', '29', ' ','31', ' ', '33', ' ', '35', ' ','37', ' ', '39', ' ']
                    });
                    
                    return {
                        version: '1.0',
                        response: {
                            outputSpeech: {
                                type: 'PlainText',
                                text: 'Your financial chart has been generated and saved to your dashboard.'
                            },
                            shouldEndSession: true
                        }
                    };

                    console.log('lifeExpectancy',lifeExpectancy)
                }
            }
            
            // Default Alexa response
            return {
                version: '1.0',
                response: {
                    outputSpeech: {
                        type: 'PlainText',
                        text: 'Welcome to your financial assistant. You can ask me to generate a chart.'
                    },
                    shouldEndSession: false
                }
            };
        }
        
        // Handle direct invocations (testing)
        else {
            const fileName = await generateTestChart({});
            return {
                statusCode: 200,
                body: JSON.stringify({
                    message: 'Chart generated successfully',
                    fileName: fileName
                })
            };
        }
        
    } catch (error) {
        console.error('Handler failed:', error);
        
        // Return appropriate error response based on request type
        if (event.request && event.request.type) {
            // Alexa error response
            return {
                version: '1.0',
                response: {
                    outputSpeech: {
                        type: 'PlainText',
                        text: 'Sorry, I encountered an error generating your chart. Please try again.'
                    },
                    shouldEndSession: true
                }
            };
        } else {
            // API error response
            return {
                statusCode: 500,
                body: JSON.stringify({
                    message: 'Chart generation failed',
                    error: error.message
                })
            };
        }
    }
};

// Main Handler - Fast Response with Background Chart Generation
const testNewBeforeTaxWithChartHandler = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'IntentRequest'
            && handlerInput.requestEnvelope.request.intent.name === 'testbeforetax';
    },
    
    async handle(handlerInput) {
        console.log('=== HANDLER STARTED ===');
        console.log('Intent name:', handlerInput.requestEnvelope.request.intent.name);
        console.log('=== AFTER GETTING SLOTS ===');
        
        const client = new DynamoDBClient({});
        const docClient = DynamoDBDocumentClient.from(client);
        
        try {
            console.log('=== STEP 1: Starting financial calculations ===');
            
            // ========== FINANCIAL CALCULATIONS (FAST) ==========
            const slots = handlerInput.requestEnvelope.request.intent.slots;
            const slotBeforeTax = slots.newbeforetaxTest ? parseFloat(slots.newbeforetaxTest.value) : null;
            console.log('Slot value:', slotBeforeTax); // Should be 11111
            
            console.log('=== SLOT VALUE EXTRACTED ===');
            console.log('Raw slot:', slots.newbeforetaxTest);
            console.log('slotBeforeTax:', slotBeforeTax);
                
            // Get data from database
            console.log('=== STEP 2: Querying database ===');
            const scanParams = { TableName: 'adviserAssist', Limit: 1 };
            const scanCommand = new ScanCommand(scanParams);
            const response = await docClient.send(scanCommand);
            
            console.log('Database response received, items count:', response.Items?.length || 0);
            
            if (!response.Items || response.Items.length === 0) {
                console.log('=== EARLY RETURN: No items found ===');
                return handlerInput.responseBuilder
                    .speak('Sorry, no financial information was found.')
                    .getResponse();
            }
          
            console.log('=== STEP 3: Processing database data ===');
            const item = response.Items[0];
            const currentUserBalance = item.attributes.userBalance || 0;
            const beforetaxconts = item.attributes.userConts || 0;
            const aftertaxconts = item.attributes.userContstwo || 0;
            const rate = item.attributes.retireperformance || 0;
            const withdrawals = item.attributes.userWithdrawal || 0;
            const yearsToRetire = item.attributes.userTerm || 0;
            const oldyrslasts = item.attributes.yrs2 || 0;
            const newyrslasts = item.attributes.yrs3 || 0;
            const currentAge = item.attributes.userAge || 0;
            const testconts = item.attributes.testBeforeTax || 0;

    // Add this right before your function call
            console.log('=== ABOUT TO CALL testNewBeforeTax ===');
            console.log('Parameters being passed:', {
                currentUserBalance,
                beforetaxconts,
                aftertaxconts,
                rate,
                withdrawals,
                yearsToRetire,
                oldyrslasts,
                currentAge,
                slotBeforeTax
            });
  //const testNewBeforeTax = (userBalance, userConts, userContstwo, retireperformance, userWithdrawal, userTerm, yrs, userAge, testBeforeTax) => {

const testBeforeTaxResult = testNewBeforeTax(
                currentUserBalance,
                beforetaxconts,        
                aftertaxconts,         
                rate,                  
                withdrawals,           
                yearsToRetire,         
                oldyrslasts,           
                currentAge,            
                slotBeforeTax          // Make sure this is the DynamoDB value
);
console.log('DynamoDB testBeforeTax value:',slotBeforeTax);
console.log('=== AFTER CALLING testNewBeforeTax ===');
            
            const newyrs = testBeforeTaxResult.yrs2;
            const oldyrs = testBeforeTaxResult.yrs3;
            const FV_total4 = testBeforeTaxResult.FV_total4;
            const oldfinal = testBeforeTaxResult.FV_total_2.toFixed(0);
            const newfinal = testBeforeTaxResult.Old_FV_total_2.toFixed(0);

            let oldfinalNumber = Number(oldfinal);
            let newfinalNumber = Number(newfinal);

            console.log('=== STEP 5: Formatting values beforetax test ===');
            console.log('oldfinal $',oldfinal);
            console.log('newfinal $',newfinal);

            // Format values
            const formattedoldFinal = new Intl.NumberFormat('en-US', {
                style: 'currency', currency: 'USD', maximumFractionDigits: 0
            }).format(oldfinalNumber);
            const formattednewFinal = new Intl.NumberFormat('en-US', {
                style: 'currency', currency: 'USD', maximumFractionDigits: 0
            }).format(newfinalNumber);
            const formattedCurrentBeforeTax = new Intl.NumberFormat('en-US', {
                style: 'currency', currency: 'USD', maximumFractionDigits: 0
            }).format(testconts);

            const formattedFV_total4 = new Intl.NumberFormat('en-US', {
                style: 'currency', currency: 'USD', maximumFractionDigits: 0
            }).format(FV_total4);

            const formattednewConts = new Intl.NumberFormat('en-US', {
                style: 'currency', currency: 'USD', maximumFractionDigits: 0
            }).format(slotBeforeTax);

            const formattedCurrentNewConts = new Intl.NumberFormat('en-US', {
                style: 'currency', currency: 'USD', maximumFractionDigits: 0
            }).format(aftertaxconts);

            console.log('Formatted values:', {
                formattedCurrentBeforeTax,
                formattednewConts
            });

 // Update database
console.log('=== STEP 6: Updating database ===');
console.log('Update values before DB update:', {
    testBeforeTax: slotBeforeTax,
    testBeforeTaxType: typeof slotBeforeTax,
    newyrs: newyrs,
    newyrsType: typeof newyrs,
    newfinalNumber: newfinalNumber,
    newfinalNumberType: typeof newfinalNumber,
    oldfinalNumber: oldfinalNumber,
    oldfinalNumberType: typeof oldfinalNumber
});

const updateParams = {
    TableName: 'adviserAssist',
    Key: { id: item.id },
    UpdateExpression: 'SET attributes.testBeforeTax = :testconts, attributes.yrs2 = :newyrs, attributes.yrs3 = :oldyrs, attributes.FV_total_2 = :newfinalNumber, attributes.Old_FV_total_2 = :oldfinalNumber',
    ExpressionAttributeValues: {
        ':testconts': Number(slotBeforeTax),
        ':newyrs': Number(newyrs),
        ':oldyrs': Number(oldyrs),
        ':oldfinalNumber': oldfinalNumber,
        ':newfinalNumber': newfinalNumber,

    }
};

console.log('DynamoDB UpdateParams:', JSON.stringify(updateParams, null, 2));

try {
    const updateCommand = new UpdateCommand(updateParams);
    const result = await docClient.send(updateCommand);
    console.log('Database update SUCCESS:', result);
} catch (updateError) {
    console.error('Database update FAILED:', updateError);
    console.error('Error details:', {
        code: updateError.name,
        message: updateError.message,
        stack: updateError.stack
    });
    throw updateError; // Re-throw to see the full error
}

            // ========== START BACKGROUND CHART GENERATION ==========
            console.log('=== STEP 7: STARTING CHART GENERATION ===');
            const userId = handlerInput.requestEnvelope.session?.user?.userId || 'anonymous';
            console.log('User ID:', userId);
            console.log('generateTestChartAsync function type:', typeof generateTestChartAsync);
            
            if (typeof generateTestChartAsync === 'function') {
                console.log('Calling generateTestChartAsync...');
                
                // Fire and forget - don't await this
                generateTestChartAsync(testBeforeTaxResult, userId).then(result => {
                    console.log('Chart generation succeeded:', result);
                }).catch(error => {
                    console.error('Background chart generation error:', error);
                });
                
                console.log('Chart generation call initiated');
            } else {
                console.error('generateTestChartAsync function not found!');
            }

            // ========== IMMEDIATE RESPONSE ==========
            console.log('=== STEP 8: Preparing response ===');

            const speechText = "<speak><break time='5s'/> The results are displayed graphically and in text so the adviser can explain their implications. To delve deeper, the adviser can tap the details button.<break time='3s'/></speak>";

            console.log('Response text prepared');

            // APL Display (simplified for debugging)
            console.log('=== STEP 9: APL logic ===');
            const __filename = fileURLToPath(import.meta.url);
            const __dirname = path.dirname(__filename);
            const testBeforeTaxChart = JSON.parse(readFileSync(path.join(__dirname, "testBeforeTax.json"), "utf-8"));
            
            function supportsAPL(handlerInput) {
                return handlerInput.requestEnvelope.context?.System?.device?.supportedInterfaces?.["Alexa.Presentation.APL"];
            }
            
            if (supportsAPL(handlerInput)) {
                handlerInput.responseBuilder.addDirective({
                    type: "Alexa.Presentation.APL.RenderDocument",
                    document: testBeforeTaxChart,
                    datasources: {
                        "retirementCalc": {
                            "retireCalcData": [{
                                "buttonStyle": "contained",
                                "vectorSource": "M23.775-0.5H11.978H0.18C-0.472-0.5-1,0.004-1,0.627v11.271v11.271c0,0.622,0.528,1.126,1.18,1.126h11.798 h11.798c0.651,0,1.18-0.504,1.18-1.126V0.627C24.955,0.004,24.427-0.5,23.775-0.5z M1.359,1.754h9.438v9.017H1.359V1.754z M1.359,13.024h9.438v9.018H1.359V13.024z M22.596,22.042h-9.438V11.897V1.754h9.438V22.042z M8.045,5.135H7.258V4.384c0-0.622-0.528-1.127-1.18-1.127c-0.651,0-1.18,0.505-1.18,1.127v0.751H4.112 c-0.651,0-1.18,0.504-1.18,1.127s0.528,1.127,1.18,1.127h0.787v0.751c0,0.623,0.528,1.127,1.18,1.127 c0.652,0,1.18-0.504,1.18-1.127V7.389h0.787c0.651,0,1.18-0.504,1.18-1.127S8.696,5.135,8.045,5.135z M8.045,16.406H4.112c-0.651,0-1.18,0.503-1.18,1.126c0,0.623,0.528,1.127,1.18,1.127h3.933 c0.651,0,1.18-0.504,1.18-1.127C9.225,16.91,8.696,16.406,8.045,16.406z M15.909,10.771h3.934c0.651,0,1.181-0.505,1.181-1.127c0-0.623-0.529-1.127-1.181-1.127h-3.934 c-0.65,0-1.179,0.505-1.179,1.127C14.73,10.266,15.259,10.771,15.909,10.771z M15.909,15.279h3.934c0.651,0,1.181-0.505,1.181-1.128c0-0.622-0.529-1.127-1.181-1.127h-3.934 c-0.65,0-1.179,0.505-1.179,1.127C14.73,14.774,15.259,15.279,15.909,15.279z",
                                "buttonString": "<p>Retirement calculations</p>."
                            }],
                            "return1": [
                                {
                            "buttonStyle": "contained",
                            "vectorSource":"M12,0.5c-6.341,0-11.5,4.935-11.5,11s5.159,11,11.5,11c6.342,0,11.5-4.935,11.5-11S18.342,0.5,12,0.5z M15.833,16.083 c0,0.334-0.188,0.641-0.494,0.803C15.195,16.962,15.036,17,14.875,17c-0.178,0-0.353-0.047-0.507-0.139l-7.667-4.583 C6.42,12.109,6.25,11.817,6.25,11.5s0.17-0.609,0.451-0.778l7.667-4.583c0.296-0.177,0.668-0.188,0.972-0.025 c0.305,0.162,0.494,0.469,0.494,0.803V16.083L15.833,16.083z",
                            "buttonString": "<p> </p>"
                          }
                        ],
                            "tick": [
                                {
                            "buttonStyle": "contained",
                            "vectorSource":"M12.5-0.5C6.149-0.5,1,4.873,1,11.5c0,6.627,5.149,12,11.5,12S24,18.127,24,11.5C24,4.873,18.851-0.5,12.5-0.5zM10.857,16.747l-4.978-5.194l1.742-1.818l3.236,3.376l6.111-6.376l1.743,1.818L10.857,16.747z",
                            "buttonString": "<p>Confirm change </p>"
                          }
                        ],
                        "update": [
                            {
                            "buttonStyle": "contained",
                            "vectorSource":"M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z",
                            "buttonString": "<p> Confirm update </p>"
                              }
                            ],
                            "home1": [
                                {
                            "buttonStyle": "contained",
                            "vectorSource":"M23.775-0.5H11.978H0.18C-0.472-0.5-1,0.004-1,0.627v11.271v11.271c0,0.622,0.528,1.126,1.18,1.126h11.798h11.798c0.651,0,1.18-0.504,1.18-1.126V0.627C24.955,0.004,24.427-0.5,23.775-0.5zM1.359,1.754h9.438v9.017H1.359V1.754zM1.359,13.024h9.438v9.018H1.359V13.024zM22.596,22.042h-9.438V11.897V1.754h9.438V22.042zM8.045,5.135H7.258V4.384c0-0.622-0.528-1.127-1.18-1.127c-0.651,0-1.18,0.505-1.18,1.127v0.751H4.112c-0.651,0-1.18,0.504-1.18,1.127s0.528,1.127,1.18,1.127h0.787v0.751c0,0.623,0.528,1.127,1.18,1.127c0.652,0,1.18-0.504,1.18-1.127V7.389h0.787c0.651,0,1.18-0.504,1.18-1.127S8.696,5.135,8.045,5.135zM8.045,16.406H4.112c-0.651,0-1.18,0.503-1.18,1.126c0,0.623,0.528,1.127,1.18,1.127h3.933c0.651,0,1.18-0.504,1.18-1.127C9.225,16.91,8.696,16.406,8.045,16.406zM15.909,10.771h3.934c0.651,0,1.181-0.505,1.181-1.127c0-0.623-0.529-1.127-1.181-1.127h-3.934c-0.65,0-1.179,0.505-1.179,1.127C14.73,10.266,15.259,10.771,15.909,10.771zM15.909,15.279h3.934c0.651,0,1.181-0.505,1.181-1.128c0-0.622-0.529-1.127-1.181-1.127h-3.934c-0.65,0-1.179,0.505-1.179,1.127C14.73,14.774,15.259,15.279,15.909,15.279z",
                            "buttonString": "<p> </p>"
                          }
                        ]
                        },


                        myTermUpdateData: { 'message': formattednewConts },
                        myTermUpdateData2: { 'message': oldyrslasts },
                        myTermUpdateData3: { 'message': newyrs },
                        myTermUpdateData4: { 'message': formattedCurrentBeforeTax },
                        myTermUpdateData5: { 'message': formattedFV_total4 },
                        myTermUpdateData6: { 'message': formattedoldFinal },
                        myTermUpdateData7: { 'message': formattednewFinal }
                    }      
                });
            }
            
            console.log('=== HANDLER ABOUT TO RETURN ===');
            return handlerInput.responseBuilder
                .speak(speechText)
                .getResponse();
                
        } catch (error) {
            console.error('=== HANDLER ERROR CAUGHT ===');
            console.error('Financial Update Error:', error);
            console.error('Error stack:', error.stack);
            return handlerInput.responseBuilder
                .speak('Sorry, there was an error processing your financial update.')               
                .getResponse();
        }
    }
};

//####################  FINISH TEST BEFORE TAX #####################



  //^^^^^^^^^^^^^Start STOP handler^^^^^^^^^^^^^^
  const StopHandler = {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return request.type === 'IntentRequest'
          && (request.intent.name === 'AMAZON.StopIntent');
      },
      handle(handlerInput) {
        
        // Convert import.meta.url to __dirname equivalent
        const __filename = fileURLToPath(import.meta.url);
        const __dirname = path.dirname(__filename);
        
        // Read the JSON file
       // const menu = JSON.parse(readFileSync(path.join(__dirname, "menu.json"), "utf-8")); // THIS SHOWS BUTTONS
        const finchatfinish = JSON.parse(readFileSync(path.join(__dirname, "finchatfinish.json"), "utf-8"));
        
        function supportsAPL(handlerInput) {
            return (
                handlerInput.requestEnvelope.context?.System?.device?.supportedInterfaces?.["Alexa.Presentation.APL"]
            );
        }
        
        if (supportsAPL(handlerInput)) {
            handlerInput.responseBuilder.addDirective({
                type: "Alexa.Presentation.APL.RenderDocument",
                document: finchatfinish,       
            });
        }

    const speechOutput = "<speak>Thank you for watching this demonstration of a revolutionary, voice-based financial planning tool. It uses Lambda, with an Alexa trigger, supported by an S3 bucket, and a dynamo db database. <break time='3s'/></speak>";
    
    return handlerInput.responseBuilder
    .speak(speechOutput)
    .withShouldEndSession(true)
    .getResponse();
    }
    };
  //^^^^^^^^^^^^^END STOP handler^^^^^^^^^^^^^^ resourcesAttributes

const ErrorHandler = {
  canHandle() {
    return true;
  },
  handle(handlerInput, error) {
    console.log(`Error handled: ${error.message}`);
    return handlerInput.responseBuilder
      .speak('Sorry, there was an error.')
      .getResponse();
  }
};

export const handler = Alexa.SkillBuilders.custom()
  .addRequestHandlers(
    LaunchRequestHandler,
    RetOverviewIntentHandler,
    GetRetvaluesIntentHandler,
    RetirmentCalcsIntentHandler,
    testNewBeforeTaxWithChartHandler,
   // updateNewBeforeTaxWithChartHandler,
   // updatedcontsChartHandler,
    StopHandler
  )
  .addErrorHandlers(ErrorHandler)
  .lambda();