/* repository.rs
 *
 * Copyright 2026 Christian Kruse
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

pub fn display_name(path: &Path) -> String {
    path.file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| path.to_string_lossy().into_owned())
}

fn generate_uuid() -> String {
    uuid::Uuid::new_v4().to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Repository {
    #[serde(default = "generate_uuid")]
    pub id: String,
    pub name: String,
    pub path: PathBuf,
    #[serde(default)]
    pub favorite: bool,
    #[serde(default)]
    pub last_opened: Option<i64>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RepositoryStore {
    pub entries: Vec<Repository>,
}

impl RepositoryStore {
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    pub fn contains_path(&self, path: &Path) -> bool {
        self.entries.iter().any(|r| r.path == path)
    }

    pub fn add(&mut self, repo: Repository) {
        self.entries.push(repo);
        self.save_or_warn();
    }

    pub fn remove(&mut self, idx: usize) -> Repository {
        let removed = self.entries.remove(idx);
        self.save_or_warn();
        removed
    }

    pub fn insert(&mut self, idx: usize, repo: Repository) {
        let insert_idx = idx.min(self.entries.len());
        self.entries.insert(insert_idx, repo);
        self.save_or_warn();
    }

    pub fn rename(&mut self, idx: usize, name: String) {
        if let Some(entry) = self.entries.get_mut(idx) {
            entry.name = name;
            self.save_or_warn();
        }
    }

    pub fn move_repo(&mut self, from: usize, to: usize) {
        if from >= self.entries.len() || from == to {
            return;
        }

        let repo = self.entries.remove(from);
        let insert_at = to.min(self.entries.len());
        self.entries.insert(insert_at, repo);

        self.save_or_warn();
    }

    pub fn set_favorite(&mut self, idx: usize, favorite: bool) {
        if let Some(entry) = self.entries.get_mut(idx) {
            entry.favorite = favorite;
            self.save_or_warn();
        }
    }

    pub fn set_last_opened(&mut self, id: &str, ts: i64) -> bool {
        if let Some(entry) = self.entries.iter_mut().find(|r| r.id == id) {
            entry.last_opened = Some(ts);
            self.save_or_warn();
            true
        } else {
            false
        }
    }

    pub fn index_of_id(&self, id: &str) -> Option<usize> {
        self.entries.iter().position(|r| r.id == id)
    }

    pub fn save_or_warn(&self) {
        if let Err(e) = save_repositories(self) {
            tracing::error!("Failed to save repositories: {e}");
        }
    }
}

fn storage_path() -> PathBuf {
    dirs::data_dir()
        .expect("Could not determine data directory")
        .join("gitte")
        .join("repositories.json")
}

pub fn load_repositories() -> (RepositoryStore, Option<String>) {
    let path = storage_path();

    match std::fs::read_to_string(&path) {
        Ok(contents) => match serde_json::from_str::<RepositoryStore>(&contents) {
            Ok(store) => {
                // Re-save so that any newly generated default IDs are persisted
                if !contents.contains("\"id\"") && !store.entries.is_empty() {
                    store.save_or_warn();
                }

                (store, None)
            }

            Err(e) => {
                tracing::warn!("Failed to parse repositories.json: {e}");

                (RepositoryStore::default(), Some(format!("Failed to parse repositories.json: {e}")))
            }
        },

        Err(_) => (RepositoryStore::default(), None),
    }
}

fn save_repositories(store: &RepositoryStore) -> std::io::Result<()> {
    let path = storage_path();

    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    let json = serde_json::to_string_pretty(store).map_err(std::io::Error::other)?;
    std::fs::write(&path, json)
}
