refactor the code to enhance readability and maintainability. Examine the following code for instances of code duplication and redundancy. Offer practical strategies for eliminating redundant code and improving code maintainability, along with explanations of why each strategy is effective in enhancing the code. Don't create functions for everything , instead create function whenever it's necessary.

def generate_results(app_manager, step):
    """
    Generate Response from LangGraph based on the user's input.

    Args:
        app_manager: Instance of AppManager class
        step: Current step in the process

    Returns:
        Updated app_manager instance
    """
    node, langgraph_state = None, None

    try:
        # Clear states and set up initial conditions
        if step == "start":
            app_manager.langgraph_states.clear()
            inputs = {
                "object_definition": app_manager.method_definition,
                "metadata": {
                    "language": app_manager.language.lower(),
                    "repo_path": os.path.abspath(app_manager.repo_path),
                    "file_path": os.path.abspath(app_manager.file_path),
                    "file_name": app_manager.file_name,
                    "object_name": app_manager.method_name,
                    "test_dir": os.path.join(
                        os.path.abspath(app_manager.repo_path), "test"
                    ),
                },
                "fca_remaining_iterations": FCA_ITERATION,
            }
            langgraph_state = langgraph_assistant(inputs=inputs)

        else:
            # Define target nodes for different steps
            target_nodes = {
                "verified_io_types": "DependencyAnalyser",
                "clarifiction_completed": "Clarifier",
                "code_generation": "ScenarioGenerator",
                "run_pytest_code": "CodeReviewer",
                "self_correction": "CodeRunner",
            }

            # Find target node state
            while app_manager.langgraph_states:
                node, langgraph_state = app_manager.langgraph_states.pop()
                if node == target_nodes.get(step):
                    app_manager.langgraph_states.append([node, langgraph_state])
                    break
            langgraph_values = langgraph_state["values"]

            # Update values based on step
            if step == "verified_io_types":
                langgraph_values["user_provided_info"] = app_manager.answers[0]
            elif step == "clarifiction_completed":
                langgraph_values["clarifier_info"] = {
                    q: app_manager.answers[i]
                    for i, q in enumerate(
                        langgraph_values["clarifier_questions"]["questions"]
                    )
                }
            elif step == "code_generation":
                langgraph_values["test_scenarios_str"] = filter_selected_scenarios(
                    scenarios_string=langgraph_values["test_scenarios_str"],
                    scenario_names=app_manager.selected_scenarios,
                )
                langgraph_values["test_scenarios_json"] = parse_scenarios(langgraph_values["test_scenarios_str"])
            elif step == "run_pytest_code":
                langgraph_values["test_code"] = app_manager.pytest_codes

            langgraph_state = langgraph_assistant(output=langgraph_values, as_node=node)

        # Update states with previous node
        prev_nodes = {
            "ScenarioGenerator": "DependencyAnalyser",
            # "ScenarioGenerator": "Clarifier",
            "FMCGenerator": "ScenarioGenerator",
            "CodeRunner": "CodeReviewer",
            "CodeReviewer": "TestCodeGenerator",
        }

        prev_node = (
            prev_nodes.get(langgraph_state["next"]) if langgraph_state["next"] else None
        )
        app_manager.langgraph_states.append([prev_node, langgraph_state])
        process_langgraph_state(app_manager)

        return app_manager.__dict__

    except Exception as ex:
        logger.error(f"Error occurred while generating results for step '{step}': {ex}")
        raise