Please optimize the following code to reduce the number of lines without altering its core logic and enhance readability. Ensure that the functionality remains intact while improving efficiency and readability.


import os
import yaml
from typing import List, Dict, Any

from dataclasses import dataclass, field
from utils.custom_logger import CustomLogger
from utils.utils import filter_selected_scenarios
from pycode_processor.repo_analyzer import find_functions_classes
from processing.result_processing import parse_scenarios
# from code_generator import langgraph_assistant
from experimental.patched_code_generator import langgraph_assistant

logger = CustomLogger.get_logger(__name__)

with open("config/config.yaml", "r", encoding="utf-8") as file:
    config = yaml.safe_load(file)

FCA_ITERATION = config["FCA_ITERATION"]


@dataclass
class AppState:
    repo_url: str = ""
    repo_path: str = ""
    repo_cloned: bool = False
    language: str = None
    file_path: str = None
    file_name: str = None
    packages: Dict[str, Any] = field(default_factory=dict)
    complete_methods: Dict[str, Any] = field(default_factory=dict)
    method_name: str = None
    method_definition: str = None
    objective: str = None
    sample_data: Any = None
    test_cases: List[Any] = field(default_factory=list)  #test_scenarios_json
    test_cases_full: List[Any] = field(default_factory=list) # test_scenarios_json
    pytest_codes: str = "" #test_code
    pytest_results: Dict[str, Any] = field(default_factory=dict) #pytest_report_str
    selected_scenarios: List[Any] = field(default_factory=list)
    questions: List[Any] = field(default_factory=list) # values['dependency_descriptions'].get(app_manager.method_name, '')
    answers: List[Any] = field(default_factory=list) # input
    messages_history: List[Any] = field(default_factory=list) # input
    components: List[Any] = field(default_factory=list) # input

    metadata: Dict[str, str] = field(default_factory=dict)
    object_definition: str = ""
    import_statements: str = ""
    clarifier_info: Dict[str, str] = field(default_factory=dict)
    clarifier_questions: Dict[str, List[str]] = field(default_factory=dict)
    test_scenarios_str: str = ""
    test_scenarios_json: Dict[str, List[Dict[str, Any]]] = field(default_factory=dict)
    fmc_code: str = ""
    test_code: str = ""
    pytest_report_json: Dict = field(default_factory=dict)
    pytest_report_str: str = ""
    fca_remaining_iterations: int = 0
    code_reviewer_suggestions: str = ""
    global_variables_and_custom_objects: str = ""
    dependency_descriptions: Dict[str, str] = field(default_factory=dict)
    scenario_codes: Dict[str, str] = field(default_factory=dict)

    def update(self, **kwargs: Dict[str, Any]) -> None:
        """Update AppState attributes based on provided keyword arguments."""
        for key, value in kwargs.items():
            if value is not None and hasattr(self, key):
                setattr(self, key, value)

    def update_and_reset(self, **kwargs: Dict[str, Any]) -> None:
        """Update certain attributes and reset the others."""
        variables_to_reset = []
        for key, value in kwargs.items():
            if hasattr(self, key):
                setattr(self, key, value)
                # Track the variable to reset
                if value is not None:
                    variables_to_reset.append(key)

        # Reset variables after the most recent update
        for key in self.__dataclass_fields__.keys():
            if key not in variables_to_reset:
                self.reset_variable(key)

    def reset_variable(self, var: str) -> None:
        """Reset a specific variable to its default value."""
        if hasattr(self, var):
            default_value = self.get_default_value(var)
            setattr(self, var, default_value)

    def get_default_value(self, var: str) -> Any:
        """Return a fresh instance value for the variable."""
        default_value = getattr(self, var)
        if isinstance(default_value, list):
            return []  # Return a new empty list
        return default_value  # Return the default for other types

    def get_state(self) -> Dict[str, Any]:
        """Get current state of all variables."""
        return {
            field.name: getattr(self, field.name)
            for field in self.__dataclass_fields__.values()
        }

    def process_file(self, file_path: str) -> Any:
        """Process the given file to extract modules and methods."""
        with open(file_path, "r", encoding="utf-8") as f:
            file_content = f.read()
            # Placeholder for function to find modules and methods
            # modules = find_import_dependencies(file_content, self.repo_path, self.language)
            methods = find_functions_classes(file_content, self.language)

        return methods

    def save_instance(self, path: str) -> None:
        """Saves the current instance to a specified file path as a pickle file."""
        import pickle

        with open(path, "wb") as file:
            pickle.dump(self, file)
        print(f"Instance saved to {path}")


def process_langgraph_state(app_manager, values, completed_step):
    """
    Process the latest state of the LangGraph.

    Args:
        app_manager: Instance of AppManager class
    """
    try:

        if completed_step == "run_pytest_code":
            app_manager.pytest_results = values["pytest_report_str"]
            app_manager.components = [
                "scenarios_section",
                "code_section",
                "results_section",
            ]

        elif completed_step == "start":
            app_manager.questions = [
                f"**Types of dependencies**\n{values['dependency_descriptions'].get(app_manager.method_name, '')}\n\n  **Please verify the io types and suggest the changes if necessary:** "
            ]
            app_manager.components = ["verify_io_user_input"]

        elif completed_step == "verified_io_types":
            app_manager.test_cases_full = values["test_scenarios_json"][
                "test_scenarios"
            ]
            app_manager.test_cases = [
                case["scenario_name"] for case in app_manager.test_cases_full
            ]
            app_manager.components = ["scenarios_section"]

        elif completed_step == "code_generation":
            app_manager.pytest_codes = values["test_code"]
            app_manager.components = ["scenarios_section", "code_section"]
        app_manager.update(**values)
    except KeyError as ke:
        logger.error(
            f"KeyError encountered while processing step {completed_step}: {ke}"
        )
        raise
    except Exception as ex:
        logger.error(f"Unexpected error occurred while processing state {ex}")
        raise

def extract_app_state_data(app_state: AppState) -> Dict:
    """
    Extract specified attributes from AppState object and return as a dictionary.
    """
    return {
        "metadata": app_state.metadata,
        "object_definition": app_state.object_definition,
        "import_statements": app_state.import_statements,
        "clarifier_info": app_state.clarifier_info,
        "clarifier_questions": app_state.clarifier_questions,
        "test_scenarios_str": app_state.test_scenarios_str,
        "test_scenarios_json": app_state.test_scenarios_json,
        "fmc_code": app_state.fmc_code,
        "test_code": app_state.test_code,
        "pytest_report_json": app_state.pytest_report_json,
        "pytest_report_str": app_state.pytest_report_str,
        "fca_remaining_iterations": app_state.fca_remaining_iterations,
        "code_reviewer_suggestions": app_state.code_reviewer_suggestions,
        "global_variables_and_custom_objects": app_state.global_variables_and_custom_objects,
        "dependency_descriptions": app_state.dependency_descriptions,
        "scenario_codes": app_state.scenario_codes,
    }

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 as dict
    """
    try:
        if step == "start":
            repo_path_abs = os.path.abspath(app_manager.repo_path)
            file_path_abs = os.path.abspath(app_manager.file_path)

            inputs = {
                "object_definition": app_manager.method_definition,
                "metadata": {
                    "language": app_manager.language.lower(),
                    "repo_path": repo_path_abs,
                    "file_path": file_path_abs,
                    "file_name": app_manager.file_name,
                    "object_name": app_manager.method_name,
                    "test_dir": os.path.join(repo_path_abs, "test"),
                },
                "fca_remaining_iterations": FCA_ITERATION,
            }

            langgraph_values = langgraph_assistant(inputs=inputs)
            completed_step = "start"
        else:
            new_values =  extract_app_state_data(app_manager)
            if step == "verified_io_types":
                new_values["user_provided_info"] = app_manager.answers[0] if app_manager.answers else ""
                as_node = "DependencyAnalyser"
            elif step == "clarification_completed":
                clarifier_questions = new_values.get("clarifier_questions", {}).get("questions", [])
                new_values["clarifier_info"] = {
                    question: app_manager.answers[i] if i < len(app_manager.answers) else ""
                    for i, question in enumerate(clarifier_questions)
                }
                as_node = "Clarifier"
            elif step == "code_generation":
                filtered_str = filter_selected_scenarios(
                    scenarios_string=new_values.get("test_scenarios_str", ""),
                    scenario_names=app_manager.selected_scenarios,
                )
                new_values["test_scenarios_str"] = filtered_str
                new_values["test_scenarios_json"] = parse_scenarios(filtered_str)
                as_node = "ScenarioGenerator"
            elif step == "run_pytest_code":
                new_values["test_code"] = app_manager.pytest_codes
                as_node = "DependencyAnalyser"

            langgraph_values = langgraph_assistant(output=new_values, as_node=as_node)
            completed_step = step

        process_langgraph_state(app_manager, langgraph_values, completed_step)

        return app_manager.__dict__

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