pub mod assist;
mod highlight;
pub mod media;
pub mod view;

use crate::agent::Agent;
use crate::app::App;
use crate::app::tabs::Tab;
use assist::Assist;
use rune::{TextEdit, Tx};
use std::time::Duration;

pub struct Editor {
    pub stem: String,
    pub edit: TextEdit,
    pub saved: String,
    pub edited_at: f64,
    pub agent: Agent,
    pub assist: Assist,
    pub generating: Option<u64>,
    pub activity: String,
}

impl Editor {
    pub fn dirty(&self) -> bool {
        self.edit.text != self.saved
    }
}

impl App {
    pub fn title(&self, stem: &str) -> String {
        self.editor(stem)
            .and_then(|e| crate::workspace::title::title(&e.edit.text))
            .or_else(|| self.ws.as_ref()?.titles.get(stem).cloned())
            .unwrap_or_else(|| stem.to_string())
    }

    pub fn editor(&self, stem: &str) -> Option<&Editor> {
        self.editors.iter().find(|e| e.stem == stem)
    }

    pub fn editor_mut(&mut self, stem: &str) -> Option<&mut Editor> {
        self.editors.iter_mut().find(|e| e.stem == stem)
    }

    pub fn open_prompt(&mut self, stem: &str) {
        if self.editor(stem).is_none() {
            let text = self
                .ws
                .as_ref()
                .map(|w| w.read_prompt(stem))
                .unwrap_or_default();
            let mut edit = TextEdit::new(&text);
            edit.focused = true;
            self.editors.push(Editor {
                stem: stem.into(),
                edit,
                saved: text,
                edited_at: 0.0,
                agent: self.cfg.default_agent,
                assist: Assist::Idle,
                generating: None,
                activity: String::new(),
            });
        }
        self.open(Tab::Prompt(stem.into()));
    }

    pub fn save_prompt(&mut self, stem: &str) {
        let Some(i) = self.editors.iter().position(|e| e.stem == stem) else {
            return;
        };
        let Some(ws) = &mut self.ws else { return };
        let text = self.editors[i].edit.text.clone();
        match ws.write_prompt(stem, &text) {
            Ok(()) => self.editors[i].saved = text,
            Err(e) => self.notice = Some(format!("could not save {stem}.md: {e}")),
        }
    }

    pub fn touch(&mut self, stem: &str, tx: &mut Tx) {
        let now = tx.clock();
        if let Some(e) = self.editor_mut(stem) {
            e.edited_at = now;
            if matches!(e.assist, Assist::Proposed { .. }) {
                e.assist = Assist::Idle;
            }
        }
        tx.wake_after(Duration::from_millis(1100));
    }

    pub(crate) fn autosave(&mut self, clock: f64, tx: &mut Tx) -> bool {
        let due: Vec<String> = self
            .editors
            .iter()
            .filter(|e| e.dirty() && clock - e.edited_at >= 1.0)
            .map(|e| e.stem.clone())
            .collect();
        for stem in &due {
            self.save_prompt(stem);
        }
        if self.editors.iter().any(|e| e.dirty()) {
            tx.wake_after(Duration::from_millis(500));
        }
        !due.is_empty()
    }

    pub fn activity(&mut self, stem: &str, line: String) {
        if let Some(e) = self.editor_mut(stem) {
            e.activity = line.clone();
        }
        if let Some(r) = self.review_mut(stem) {
            r.activity = line;
        }
    }
}
