def update_readme()

in devai-cli/src/devai/commands/document.py [0:0]


def update_readme(context, file):
    """Ureate a release notes based on the context passed!
    
    
    
    
    """
    click.echo('Reviewing and updating README ....')

    
    # open the file passed and add to variable called current
    try:
        with open(file, 'r') as f:
            current = f.read()
    except FileNotFoundError:
        click.echo(f"Error: Release Notes file provided not found: {file}")
        return
    

    source='''
            ### Context (code) ###
            
            CURRENT RELEASE NOTES: 
            {current}
            
            NEW CODE:
            {context}

            '''
    qry = get_prompt('document_update_readme') or f'''
            ### Instruction ###
            Review the CURRENT readme and ensure they are comprehensive for the provided context. The README should follow industry best practices and be suitable for professional developers. Resources like dora.dev, stc.org, and writethedocs.org should be used as guidelines.

            It should be clear, concise, and easy to read written in a professional mannor conveying the project's purpose and value effectively.
            
            Generate a new comprehensive README.md file for the provided context based on the current readme and incourporate any recomendations from the revew and changes to the context.
            
            Should be a two part output. Part 1 discussion of the existing, current, readme. 
            
            Part 2 should update the readme incorporating the discussion points and and any changes to the code accurately reflect the changes and improvements introduced.

           

            ### Output Format ### 
            Split into two parts seperated by the line "============== FEEDBACK ^^ ========= NEW VERSION vv =============" . 

            Part 1: Discussion and review of CURRENT should be above and part 2 should be below this line.
            
            The updated version should continue to be a well-structured README.md file in Markdown format. The README, using markdown formatting, should incorporate updates recommended in part 1, incorporate the new code context and include the following sections (at a minimum):

            Description
            Table of Contents
            Features
            Installation
            Usage
            Contributing
            License
            Contact

            ### Example Dialogue ###
            Feedback on the current readme is;
            **Strengths:**

            * **Well-organized:** The README follows a logical structure with clear headings, making it easy to navigate.
            * **Comprehensive sections:** It covers important aspects like Features, Architecture, Technologies, and Installation.
            * **Clear installation instructions:**  The steps are concise and provide the necessary prerequisites.
            * **Configuration details:** It highlights the required environment variables.
            * **Basic usage example:**  Provides simple API endpoint examples. 
            * **Contribution guidelines and license:**  Links to relevant files, encouraging community involvement.
            * **Contact information:** Offers a way to get in touch for support.

            **Areas for Improvement:**

            * **Description:** The description is a good start but could be more engaging and clearly articulate the value proposition of the Balance Reader microservice. 
            * **Target audience:** Consider explicitly stating the intended audience for this README (e.g., developers who will integrate with the service, those deploying it).
            * **Code examples:**  Include more concrete code snippets for using the API (e.g., making authenticated requests).
            * **Error handling:**  Mention how the service handles errors and what responses users can expect.
            * **Assumptions:**  Are there any assumptions about the environment or dependencies that should be documented?
            * **Testing:** Add a section about how to run tests for the project.

            
            ============== FEEDBACK ^^ ========= NEW VERSION vv =============
            
            # Balance Reader Microservice

            [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

            ## Table of Contents

            - [Description](#description)
            - [Features](#features)
            - [Architecture](#architecture)
            - [Technologies](#technologies)
            - [Installation](#installation)
            - [Configuration](#configuration)
            - [Usage](#usage)
            - [Testing](#testing)
            - [Contributing](#contributing)
            - [License](#license)
            - [Contact](#contact)

            ## Description

            The Balance Reader is a crucial microservice within the Bank of Anthos application, a cloud-native banking platform. Its primary responsibility is to securely and efficiently provide account balance information to authorized users and services.  Built with performance and scalability in mind, it leverages caching and real-time transaction processing to ensure accurate and up-to-date balance retrieval.

            **Target Audience:** This documentation is intended for developers integrating with the Balance Reader API and DevOps engineers responsible for its deployment and management.

            ## Features

            * **Secure Balance Retrieval:** Utilizes JWT-based authentication to enforce strict access control, ensuring only authorized entities can retrieve account balances.
            * **Efficient Caching:**  Implements a Guava LoadingCache to optimize performance by caching frequently accessed account balances, reducing database load and latency.
            * **Real-time Balance Updates:** A dedicated Ledger Reader component continuously monitors the transaction database, updating the cache in real-time to reflect the latest transactions. 
            * **Health Checks:** Exposes readiness and liveness probes, allowing Kubernetes to monitor the service's operational status and ensure high availability.
            * **Metrics Instrumentation:** Integrates with Stackdriver for comprehensive performance monitoring using key performance indicators.

            ## Architecture

            The Balance Reader follows a layered architecture:

            - **Controller (`BalanceReaderController`):** The entry point for incoming HTTP requests.  It handles user authentication, interacts with the cache, and delegates transaction processing to the Ledger Reader.
            - **Service (`LedgerReader`):**  Continuously polls for new transactions, updates the cache, and maintains balance consistency.
            - **Repository (`TransactionRepository`):**  Provides an abstraction layer for accessing the transaction database, enabling balance calculations and transaction retrieval.
            - **Cache (`BalanceCache`):**  Stores recently accessed account balances to minimize database interactions and improve response times.
            - **Model (`Transaction`):** Represents a single transaction within the system.

            ## Technologies

            - Java
            - Spring Boot
            - Spring Data JPA
            - Guava Cache
            - JWT (JSON Web Tokens)
            - Micrometer
            - Stackdriver
            - Kubernetes

            ## Installation

            1. **Prerequisites:**
            - Java Development Kit (JDK) 8 or later
            - Maven (or another compatible Java build tool)
            - Docker (for containerization)

            2. **Clone the Repository:**
            ```bash
            git clone https://github.com/your-organization/balance-reader.git 
            ```

            3. **Build the Application:**
            ```bash
            cd balance-reader
            mvn clean install
            ```

            ## Configuration

            The Balance Reader service uses environment variables for configuration. Ensure the following variables are set:

            | Variable                 | Description                                      |
            | ----------------------- | ------------------------------------------------ |
            | `VERSION`                | Service version.                               |
            | `PORT`                   | Port to listen on.                             |
            | `LOCAL_ROUTING_NUM`     | Bank routing number for the service instance.   |
            | `PUB_KEY_PATH`          | Path to the public key for JWT verification.  |
            | `SPRING_DATASOURCE_URL` | JDBC URL for the database.                    |
            | `SPRING_DATASOURCE_USERNAME` | Database username.                          |
            | `SPRING_DATASOURCE_PASSWORD` | Database password.                          |
            | `ENABLE_METRICS`         | Set to 'false' to disable metrics export.       | 

            You can set these variables directly in your environment or use a configuration management tool.


            ## Usage

            1. **Start the Application:**
            ```bash
            java -jar target/balance-reader.jar
            ```

            2. **Access the API Endpoints:**

            -  /version:  Retrieve the service version.
            -  /ready:  Check service readiness.
            -  /healthy:  Check service health.
            -  /balances/accountId: Retrieve the balance for the given account ID (requires a valid JWT in the `Authorization` header). 

                **Example Request (Retrieve Balance):**
                ```bash 
                curl -H "Authorization: Bearer your_jwt_token" http://localhost:8080/balances/account123
                ```
            
                **Error Handling:** The service returns standard HTTP status codes to indicate success or failure. For example, 401 Unauthorized for invalid JWTs and 500 Internal Server Error for internal errors.  Error messages will be included in the response body. 

            ## Testing
            Run unit and integration tests using Maven:
            ```bash
            mvn test
            ```

            ## Contributing

            We welcome contributions! Please refer to the [CONTRIBUTING.md](CONTRIBUTING.md) file for guidelines on contributing to this project.

            ## License

            This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE) file for details.

            ## Contact

            For any questions or support requests, please open an issue on the [GitHub repository](https://git.cymbal.coffee). 

            '''

   
    source=source.format(current=current, context=format_files_as_string(context))
    
    code_chat_model = GenerativeModel(MODEL_NAME)
    with telemetry.tool_context_manager(USER_AGENT):
        code_chat = code_chat_model.start_chat()
        code_chat.send_message(qry)
        response = code_chat.send_message(source)

    click.echo(f"{response.text}")