#include "profile_config.h"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <pwd.h>
#include <random>
#include <sstream>
#include <sys/stat.h>
#include <unistd.h>

namespace fs = std::filesystem;

ProfileConfig::ProfileConfig() { load(); }

std::string ProfileConfig::getConfigDir() {
  return "/etc/peak";
}

std::string ProfileConfig::getConfigPath() {
  return getConfigDir() + "/browser.conf";
}

void ProfileConfig::load() {
  std::string config_path = getConfigPath();
  std::ifstream file(config_path);

  if (!file.good()) {
    createDefaultConfig();
    return;
  }

  std::string line;
  while (std::getline(file, line)) {
    if (line.empty() || line[0] == '#')
      continue;

    size_t eq = line.find('=');
    if (eq == std::string::npos)
      continue;

    std::string key = trim(line.substr(0, eq));
    std::string value = trim(line.substr(eq + 1));

    if (key == "profile_mode") {
      if (value == "temporary")
        mode_ = ProfileMode::Temporary;
      else if (value == "persistent")
        mode_ = ProfileMode::Persistent;
      else if (value == "custom")
        mode_ = ProfileMode::Custom;
    } else if (key == "profile_path") {
      custom_path_ = value;
    } else if (key == "cache_size_mb") {
      try {
        cache_size_mb_ = std::stoul(value);
      } catch (...) {
      }
    } else if (key == "clear_cache_on_exit") {
      clear_cache_on_exit_ = (value == "true");
    } else if (key == "clear_cookies_on_exit") {
      clear_cookies_on_exit_ = (value == "true");
    } else if (key == "default_url") {
      default_url_ = value;
    } else if (key == "grid_keys") {
      if (value.length() == 9) {
        grid_keys_ = value;
      }
    } else if (key == "doh_enabled") {
      doh_enabled_ = (value == "true");
    } else if (key == "doh_server") {
      doh_server_ = value;
    } else if (key == "doh_mode") {
      doh_mode_ = value;
    } else if (key == "tiled_rendering") {
      tiled_rendering_enabled_ = (value == "true");
    } else if (key == "cell_width") {
      cell_width_override_ = std::stoi(value);
    } else if (key == "cell_height") {
      cell_height_override_ = std::stoi(value);
    } else if (key == "graphics_protocol") {
      if (value == "sixel" || value == "kitty" ||
          value == "framebuffer") {
        graphics_protocol_ = value;
      }
    } else if (key == "show_internal_console_logs") {
      show_internal_console_logs_ = (value == "true");
    } else if (key == "proxy_enabled") {
      proxy_enabled_ = (value == "true");
    } else if (key == "proxy_server") {
      proxy_server_ = value;
    } else if (key == "proxy_bypass_list") {
      proxy_bypass_list_ = value;
    } else if (key == "proxy_username") {
      proxy_username_ = value;
    } else if (key == "proxy_password") {
      proxy_password_ = value;
    } else if (key == "zoom_level") {
      try {
        zoom_level_ = std::stod(value);
      } catch (...) {
      }
    } else if (key == "zoom_step") {
      try {
        zoom_step_ = std::stod(value);
      } catch (...) {
      }
    } else if (key == "default_zoom_behavior") {
      if (value == "auto" || value == "fixed" || value == "none") {
        default_zoom_behavior_ = value;
      }
    }
  }
  file.close();
  
  // Load site-specific zoom levels from zoom.conf
  loadSiteZoomLevels();
}

void ProfileConfig::save() {
  std::string config_path = getConfigPath();
  std::ofstream file(config_path);

  if (!file.is_open()) {
    std::cerr << "Failed to save browser config" << std::endl;
    return;
  }

  writeConfig(file, false, false);
  file.close();
}

void ProfileConfig::writeConfig(std::ofstream &file, bool use_defaults,
                                bool include_examples) {
  file << "# Browser Profile Configuration\n";
  file << "# Generated by peak\n";
  file << "\n";
  file << "# Profile mode: temporary, persistent, or custom\n";
  file << "# - temporary: New profile each session, deleted on exit (private "
          "mode)\n";
  file << "# - persistent: Profile saved at /etc/peak/profile\n";
  file << "# - custom: Use profile_path below\n";

  if (use_defaults) {
    file << "profile_mode=temporary\n";
  } else {
    switch (mode_) {
    case ProfileMode::Temporary:
      file << "profile_mode=temporary\n";
      break;
    case ProfileMode::Persistent:
      file << "profile_mode=persistent\n";
      break;
    case ProfileMode::Custom:
      file << "profile_mode=custom\n";
      break;
    }
  }

  file << "\n";
  file << "# Profile path (only used when profile_mode=custom)\n";
  file << "# Can use ~ for home directory\n";
  file << "profile_path="
       << (use_defaults ? "/etc/peak/profile" : custom_path_) << "\n";
  file << "\n";
  file << "# Cache settings\n";
  file << "cache_size_mb=" << (use_defaults ? 500 : cache_size_mb_) << "\n";
  file << "clear_cache_on_exit="
       << (use_defaults ? "false" : (clear_cache_on_exit_ ? "true" : "false"))
       << "\n";
  file << "\n";
  file << "# Privacy options"
       << (use_defaults ? " (for persistent/custom profiles)" : "") << "\n";
  file << "clear_cookies_on_exit="
       << (use_defaults ? "false" : (clear_cookies_on_exit_ ? "true" : "false"))
       << "\n";

  if (include_examples) {
    file << "\n";
    file << "# Examples:\n";
    file << "# For normal browsing with saved sessions:\n";
    file << "#   profile_mode=persistent\n";
    file << "#\n";
    file << "# For custom profile location:\n";
    file << "#   profile_mode=custom\n";
    file << "#   profile_path=/path/to/my/profile\n";
    file << "#\n";
    file << "# For semi-private (settings persist, cache cleared):\n";
    file << "#   profile_mode=persistent\n";
    file << "#   clear_cache_on_exit=true\n";
    file << "#   clear_cookies_on_exit=true\n";
  }

  file << "\n";
  file << "# Default homepage URL\n";
  file << "default_url="
       << (use_defaults ? "https://example.com" : default_url_) << "\n";
  file << "\n";
  file << "# Grid keys for mouse emulation grid jump mode (must be exactly 9 "
          "characters)\n";
  file << "# Default: qweasdzxc (3x3 grid matching keyboard layout)\n";
  file << "# Alternative: abcdefghi (alphabetical)\n";
  file << "grid_keys=" << (use_defaults ? "qweasdzxc" : grid_keys_) << "\n";
  file << "\n";
  file << "# DNS-over-HTTPS (DoH) Configuration\n";
  file << "# Enable secure DNS to encrypt DNS queries\n";
  file << "doh_enabled="
       << (use_defaults ? "false" : (doh_enabled_ ? "true" : "false")) << "\n";
  file << "doh_server="
       << (use_defaults ? "https://cloudflare-dns.com/dns-query" : doh_server_)
       << "\n";
  file << "doh_mode=" << (use_defaults ? "secure" : doh_mode_) << "\n";
  file << "# DoH mode options:\n";
  file << "#   secure: Mandatory DoH, no fallback (recommended for blocking)\n";
  file << "#   automatic: Use DoH when available, fallback to system DNS\n";
  file << "#   off: Disable DoH\n";
  file << "# Popular DoH servers:\n";
  file << "#   Cloudflare: https://cloudflare-dns.com/dns-query\n";
  file << "#   Google: https://dns.google/dns-query\n";
  file << "#   Quad9: https://dns.quad9.net/dns-query\n";
  file << "\n";
  file << "# Tiled Rendering\n";
  file << "# Enable tile-based sixel rendering (reduces flicker on updates)\n";
  file << "# When enabled, only changed screen regions are redrawn\n";
  file << "# When disabled, the entire screen is redrawn on every update "
          "(default)\n";
  file << "# NOTE: Only applies to sixel protocol. Kitty protocol always uses "
          "full-frame rendering.\n";
  file << "tiled_rendering="
       << (use_defaults ? "false"
                        : (tiled_rendering_enabled_ ? "true" : "false"))
       << "\n";
  file << "\n";
  file << "# Terminal Cell Dimensions (optional override)\n";
  file << "# Leave at 0 for auto-detection (recommended)\n";
  file << "# Only override if auto-detection produces incorrect results\n";
  file << "#cell_width="
       << (use_defaults ? "0" : std::to_string(cell_width_override_)) << "\n";
  file << "#cell_height="
       << (use_defaults ? "0" : std::to_string(cell_height_override_)) << "\n";
  file << "\n";
  file << "# Graphics Protocol\n";
  file << "# Choose between 'sixel' (default, widely supported) or 'kitty' "
          "(kitty terminal protocol)\n";
  file << "# sixel: Traditional sixel graphics (recommended for most terminals)\n";
  file << "# kitty: Kitty graphics protocol (for kitty, ghostty, wezterm, etc.)\n";
  file << "# framebuffer: Direct /dev/fb0 blitting (only on a plain fb console TTY)\n";
  file << "graphics_protocol="
       << (use_defaults ? "sixel" : graphics_protocol_) << "\n";
  file << "\n";
  file << "# Show internal console messages\n";
  file << "# When false, hides internal [peak] debug messages from JS console\n";
  file << "# Set to true if you need to debug browser internals\n";
  file << "show_internal_console_logs="
       << (use_defaults ? "false" : (show_internal_console_logs_ ? "true" : "false"))
       << "\n";
  file << "\n";
  file << "# Proxy Configuration\n";
  file << "# Route browser traffic through HTTP/HTTPS/SOCKS proxy\n";
  file << "proxy_enabled="
       << (use_defaults ? "false" : (proxy_enabled_ ? "true" : "false")) << "\n";
  file << "# Proxy server format: scheme://host:port (NO credentials in URL)\n";
  file << "# Supported schemes: http://, https://, socks4://, socks5://\n";
  file << "# Examples:\n";
  file << "#   proxy_server=socks5://127.0.0.1:1080\n";
  file << "#   proxy_server=http://proxy.example.com:8080\n";
  file << "#   proxy_server=https://secure-proxy.example.com:443\n";
  file << "proxy_server=" << (use_defaults ? "" : proxy_server_) << "\n";
  file << "# Proxy authentication (optional)\n";
  file << "# If proxy requires authentication, provide credentials here\n";
  file << "# Leave empty for no authentication or interactive prompt\n";
  file << "proxy_username=" << (use_defaults ? "" : proxy_username_) << "\n";
  file << "proxy_password=" << (use_defaults ? "" : proxy_password_) << "\n";
  file << "# Bypass proxy for these hosts (comma-separated)\n";
  file << "proxy_bypass_list="
       << (use_defaults ? "localhost,127.0.0.1" : proxy_bypass_list_) << "\n";
  
  file << "\n";
  file << "# Zoom Configuration\n";
  file << "# Default zoom level (1.0 = 100%, 2.0 = 200%)\n";
  file << "zoom_level=" << (use_defaults ? "1.0" : std::to_string(zoom_level_)) << "\n";
  file << "# Zoom step size for +/- adjustments\n";
  file << "zoom_step=" << (use_defaults ? "0.5" : std::to_string(zoom_step_)) << "\n";
  file << "# Default zoom behavior: auto, fixed, or none\n";
  file << "# - auto: Automatically adjust zoom based on terminal cell size/DPI\n";
  file << "#         (larger cells = zoom in, smaller cells = zoom out)\n";
  file << "# - fixed: Use zoom_level setting at startup\n";
  file << "# - none: Start at 1.0 (100%), manual adjustment only\n";
  file << "default_zoom_behavior=" << (use_defaults ? "none" : default_zoom_behavior_) << "\n";
  file << "#\n";
  file << "# Per-site zoom levels are configured in /etc/peak/zoom.conf\n";
  file << "# (Site-specific settings override auto/fixed behavior)\n";
}

std::string ProfileConfig::getProfilePath() const {
  switch (mode_) {
  case ProfileMode::Temporary:
    return ""; // Will be generated
  case ProfileMode::Persistent:
    return "/etc/peak/profile";
  case ProfileMode::Custom:
    return expandPath(custom_path_);
  }
  return "";
}

std::string ProfileConfig::createProfileDirectory() {
  std::string path;

  switch (mode_) {
  case ProfileMode::Temporary: {
    // Create unique temporary directory
    path = "/tmp";

    // Add unique identifier with PID and random number
    std::random_device rd;
    path += "/peak_" + std::to_string(getpid()) + "_" + std::to_string(rd());
    break;
  }

  case ProfileMode::Persistent:
    path = "/etc/peak/profile";
    break;

  case ProfileMode::Custom:
    path = expandPath(custom_path_);
    if (path.empty()) {
      std::cerr << "Custom profile path is empty, falling back to persistent"
                << std::endl;
      path = "/etc/peak/profile";
    }
    break;
  }

  // Create directory if it doesn't exist
  std::error_code ec;
  fs::create_directories(path, ec);

  if (ec) {
    std::cerr << "Failed to create profile directory '" << path
              << "': " << ec.message() << std::endl;
    return "";
  }

// Set permissions (Unix) - owner only for security
#ifndef _WIN32
  fs::permissions(path, fs::perms::owner_all, fs::perm_options::replace, ec);
  if (ec) {
    std::cerr << "Warning: Failed to set profile permissions: " << ec.message()
              << std::endl;
  }
#endif

  current_profile_path_ = path;

  // Log profile info
  const char *mode_str = "";
  switch (mode_) {
  case ProfileMode::Temporary:
    mode_str = "temporary";
    break;
  case ProfileMode::Persistent:
    mode_str = "persistent";
    break;
  case ProfileMode::Custom:
    mode_str = "custom";
    break;
  }
  std::cout << "Profile mode: " << mode_str << std::endl;
  std::cout << "Profile path: " << path << std::endl;

  return path;
}

void ProfileConfig::cleanupProfile() {
  if (current_profile_path_.empty())
    return;

  std::cout << "Cleaning up profile..." << std::endl;

  // Always delete temporary profiles
  if (mode_ == ProfileMode::Temporary) {
    std::error_code ec;
    fs::remove_all(current_profile_path_, ec);
    if (ec) {
      std::cerr << "Failed to cleanup profile: " << ec.message() << std::endl;
    } else {
      std::cout << "Temporary profile deleted" << std::endl;
    }
    return;
  }

  // For persistent/custom profiles, handle selective cleanup
  if (clear_cache_on_exit_) {
    std::error_code ec;
    fs::path cache_dir = fs::path(current_profile_path_) / "cache";
    if (fs::exists(cache_dir)) {
      fs::remove_all(cache_dir, ec);
      if (!ec) {
        std::cout << "Cache cleared" << std::endl;
      }
    }

    // Also clear GPUCache
    fs::path gpu_cache = fs::path(current_profile_path_) / "GPUCache";
    if (fs::exists(gpu_cache)) {
      fs::remove_all(gpu_cache, ec);
    }
  }

  if (clear_cookies_on_exit_) {
    // Clear cookies file
    fs::path cookies = fs::path(current_profile_path_) / "Cookies";
    std::error_code ec;
    if (fs::exists(cookies)) {
      fs::remove(cookies, ec);
      if (!ec) {
        std::cout << "Cookies cleared" << std::endl;
      }
    }

    // Also clear Cookies-journal
    fs::path cookies_journal =
        fs::path(current_profile_path_) / "Cookies-journal";
    if (fs::exists(cookies_journal)) {
      fs::remove(cookies_journal, ec);
    }
  }
}

void ProfileConfig::overrideMode(const std::string &mode_str) {
  if (mode_str == "persistent") {
    mode_ = ProfileMode::Persistent;
    std::cout << "Profile mode overridden to: persistent" << std::endl;
  } else if (mode_str == "temporary") {
    mode_ = ProfileMode::Temporary;
    std::cout << "Profile mode overridden to: temporary" << std::endl;
  } else if (mode_str == "custom") {
    mode_ = ProfileMode::Custom;
    std::cout << "Profile mode overridden to: custom" << std::endl;
  } else {
    std::cerr << "Unknown profile mode: " << mode_str << std::endl;
  }
}

void ProfileConfig::createDefaultConfig() {
  std::string config_dir = getConfigDir();
  std::string config_path = getConfigPath();

  // Ensure directory exists
  struct stat st;
  if (stat(config_dir.c_str(), &st) != 0) {
    mkdir(config_dir.c_str(), 0755);
  }

  std::ofstream file(config_path);
  if (!file.is_open()) {
    std::cerr << "Failed to create default browser config" << std::endl;
    return;
  }

  writeConfig(file, true, true);
  file.close();
}

std::string ProfileConfig::expandPath(const std::string &path) const {
  if (path.empty() || path[0] != '~')
    return path;

  const char *home = getenv("HOME");
  if (!home) {
    struct passwd *pw = getpwuid(getuid());
    if (pw) {
      home = pw->pw_dir;
    }
  }

  if (!home)
    return path;
  return std::string(home) + path.substr(1);
}

std::string ProfileConfig::trim(const std::string &str) {
  size_t first = str.find_first_not_of(" \t\r\n");
  if (first == std::string::npos) {
    return "";
  }
  size_t last = str.find_last_not_of(" \t\r\n");
  return str.substr(first, last - first + 1);
}

double ProfileConfig::getSiteZoomLevel(const std::string &domain) const {
  auto it = site_zoom_levels_.find(domain);
  if (it != site_zoom_levels_.end()) {
    return it->second;
  }
  // Check for subdomain match (e.g., www.github.com matches github.com)
  for (const auto &entry : site_zoom_levels_) {
    if (domain.find(entry.first) != std::string::npos) {
      return entry.second;
    }
  }
  return zoom_level_; // Return default zoom level
}

void ProfileConfig::loadSiteZoomLevels() {
  site_zoom_levels_.clear();
  
  std::string zoom_conf_path = getConfigDir() + "/zoom.conf";
  std::ifstream file(zoom_conf_path);
  
  if (!file.good()) {
    // Create default zoom.conf with examples
    std::ofstream out(zoom_conf_path);
    if (out.is_open()) {
      out << "# Site-specific zoom levels\n";
      out << "# Format: domain=zoom_level\n";
      out << "# zoom_level is a multiplier: 1.0 = 100%, 2.0 = 200%, 0.5 = 50%\n";
      out << "#\n";
      out << "# Examples:\n";
      out << "# github.com=1.5\n";
      out << "# wikipedia.org=1.25\n";
      out << "# reddit.com=2.0\n";
      out.close();
    }
    return;
  }
  
  std::string line;
  while (std::getline(file, line)) {
    if (line.empty() || line[0] == '#')
      continue;
      
    size_t eq = line.find('=');
    if (eq == std::string::npos)
      continue;
      
    std::string domain = trim(line.substr(0, eq));
    std::string value = trim(line.substr(eq + 1));
    
    try {
      site_zoom_levels_[domain] = std::stod(value);
    } catch (...) {
      // Ignore invalid lines
    }
  }
  file.close();
}
