// SPDX-License-Identifier: Apache-2.0
// Copyright 2025 C++ Best Practices Example
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @file example_cpp_best_practices.cpp
 * @brief Demonstrates modern C++ best practices following industry guidelines
 * @author Generated Example
 * @date 2025
 */

#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <algorithm>
#include <stdexcept>
#include <cassert>

namespace best_practices {

/**
 * @brief A simple class demonstrating RAII, const-correctness, and modern C++ features
 */
class ResourceManager {
private:
    std::unique_ptr<std::vector<int>> data_;
    std::string name_;
    
public:
    /**
     * @brief Constructor with parameter validation
     * @param name The name of the resource manager
     * @throws std::invalid_argument if name is empty
     */
    explicit ResourceManager(const std::string& name) 
        : data_(std::make_unique<std::vector<int>>()), name_(name) {
        if (name.empty()) {
            throw std::invalid_argument("Name cannot be empty");
        }
    }
    
    // Rule of 5: Define copy/move constructors and assignment operators
    ResourceManager(const ResourceManager& other) 
        : data_(std::make_unique<std::vector<int>>(*other.data_)), 
          name_(other.name_) {}
    
    ResourceManager(ResourceManager&& other) noexcept 
        : data_(std::move(other.data_)), name_(std::move(other.name_)) {}
    
    ResourceManager& operator=(const ResourceManager& other) {
        if (this != &other) {
            data_ = std::make_unique<std::vector<int>>(*other.data_);
            name_ = other.name_;
        }
        return *this;
    }
    
    ResourceManager& operator=(ResourceManager&& other) noexcept {
        if (this != &other) {
            data_ = std::move(other.data_);
            name_ = std::move(other.name_);
        }
        return *this;
    }
    
    // Destructor (default is fine due to RAII)
    ~ResourceManager() = default;
    
    /**
     * @brief Add an element to the managed data
     * @param value The value to add
     */
    void addElement(int value) {
        data_->push_back(value);
    }
    
    /**
     * @brief Get the name of the resource manager
     * @return const reference to the name
     */
    const std::string& getName() const noexcept {
        return name_;
    }
    
    /**
     * @brief Get the size of managed data
     * @return size of the data vector
     */
    std::size_t size() const noexcept {
        return data_->size();
    }
    
    /**
     * @brief Get element at index with bounds checking
     * @param index The index to access
     * @return const reference to the element
     * @throws std::out_of_range if index is invalid
     */
    const int& at(std::size_t index) const {
        return data_->at(index);
    }
    
    /**
     * @brief Apply a function to all elements
     * @tparam Func Function type
     * @param func Function to apply
     */
    template<typename Func>
    void forEach(Func&& func) const {
        std::for_each(data_->begin(), data_->end(), std::forward<Func>(func));
    }
};

/**
 * @brief Factory function for creating ResourceManager instances
 * @param name The name for the resource manager
 * @return unique_ptr to ResourceManager
 */
std::unique_ptr<ResourceManager> createResourceManager(const std::string& name) {
    return std::make_unique<ResourceManager>(name);
}

/**
 * @brief Utility function demonstrating algorithm usage and const-correctness
 * @param values Vector of values to process
 * @return Vector containing only even values, sorted
 */
std::vector<int> processEvenValues(const std::vector<int>& values) {
    std::vector<int> result;
    
    // Use standard algorithms instead of raw loops
    std::copy_if(values.begin(), values.end(), std::back_inserter(result),
                 [](int value) { return value % 2 == 0; });
    
    std::sort(result.begin(), result.end());
    
    return result;
}

/**
 * @brief Demonstrates exception safety and RAII
 */
void demonstrateExceptionSafety() {
    try {
        auto manager = createResourceManager("ExampleManager");
        
        // Add some test data
        for (int i = 1; i <= 10; ++i) {
            manager->addElement(i);
        }
        
        std::cout << "Manager '" << manager->getName() 
                  << "' contains " << manager->size() << " elements\n";
        
        // Demonstrate safe access
        try {
            std::cout << "Element at index 5: " << manager->at(5) << "\n";
            std::cout << "Element at index 100: " << manager->at(100) << "\n"; // Will throw
        } catch (const std::out_of_range& e) {
            std::cout << "Caught expected exception: " << e.what() << "\n";
        }
        
        // Demonstrate algorithm usage
        std::cout << "Elements: ";
        manager->forEach([](int value) { std::cout << value << " "; });
        std::cout << "\n";
        
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << "\n";
        throw; // Re-throw to maintain exception safety
    }
}

} // namespace best_practices

/**
 * @brief Main function demonstrating the usage
 */
int main() {
    try {
        std::cout << "=== C++ Best Practices Example ===\n\n";
        
        // Demonstrate resource management
        best_practices::demonstrateExceptionSafety();
        
        // Demonstrate algorithm usage
        std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        auto evenNumbers = best_practices::processEvenValues(numbers);
        
        std::cout << "\nOriginal numbers: ";
        for (const auto& num : numbers) {
            std::cout << num << " ";
        }
        
        std::cout << "\nEven numbers (sorted): ";
        for (const auto& num : evenNumbers) {
            std::cout << num << " ";
        }
        std::cout << "\n";
        
        std::cout << "\n=== Example completed successfully ===\n";
        
    } catch (const std::exception& e) {
        std::cerr << "Fatal error: " << e.what() << "\n";
        return 1;
    } catch (...) {
        std::cerr << "Unknown fatal error occurred\n";
        return 1;
    }
    
    return 0;
}