mod agent;
mod cli;
mod config;
mod error;
mod llm;
mod tools;
mod ui;
mod utils;

use agent::Agent;
use clap::Parser;
use cli::AgentHinter;
use error::Error;
use rustyline::error::ReadlineError;
use rustyline::history::DefaultHistory;
use rustyline::Editor;
use std::path::PathBuf;
use ui::UI;

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {}

#[tokio::main]
async fn main() -> Result<(), Error> {
    // 1. 指定工作目录
    let ariste_folder: PathBuf = ".ariste".into();
    if !ariste_folder.exists() {
        tokio::fs::create_dir_all(&ariste_folder).await?;
    }

    // 2. 创建Agent和UI
    let mut agent = Agent::load_from_config().await?;
    let mut ui = UI::new();

    // 3. 显示欢迎信息
    let workdir: PathBuf = std::env::current_dir()?;
    UI::welcome(&workdir);

    let mut rl: Editor<AgentHinter, DefaultHistory> = Editor::new()?;
    let history_file = ariste_folder.join("history.txt");
    if history_file.exists() {
        rl.load_history(&history_file)?;
    }
    rl.set_helper(Some(AgentHinter::new()));

    // 4. 聊天对话
    loop {
        let prompt = UI::prompt();
        match rl.readline(&prompt) {
            Ok(line) => {
                let line = line.trim();
                rl.add_history_entry(line)?;

                // 处理命令
                match line {
                    "/q" | "/quit" | "/exit" => {
                        UI::clear_previous_line();
                        agent.quit().await?;
                        UI::goodbye();
                        break;
                    }
                    "/help" => {
                        UI::welcome(&workdir);
                        continue;
                    }
                    "/clear" => {
                        agent.clear_history();
                        UI::clear();
                        UI::welcome(&workdir);
                        UI::info("Conversation history cleared");
                        continue;
                    }
                    cmd if cmd.starts_with('/') => {
                        UI::warning(&format!("Unknown command: {}", cmd));
                        UI::info("Type /help to see available commands");
                        continue;
                    }
                    _ => {
                        // 执行 AI 调用
                        ui.reset_spinner();
                        if let Err(e) = agent.invoke(line).await {
                            UI::error(&e.to_string());
                        }
                        UI::response_end();
                    }
                }
            }
            Err(ReadlineError::Interrupted) => {
                UI::info("Use /quit to exit the program");
                continue;
            }
            Err(ReadlineError::Eof) => {
                UI::clear_previous_line();
                agent.quit().await?;
                UI::goodbye();
                break;
            }
            Err(err) => {
                UI::error(&format!("Error: {:?}", err));
                continue;
            }
        }
    }

    // 5. 保存历史信息
    rl.save_history(&history_file)?;

    Ok(())
}
