//! Stdio entry point for kon-mcp. Reads newline-delimited JSON-RPC messages
//! from stdin, dispatches via `kon_mcp::handle_message`, writes responses to
//! stdout. Logs land on stderr so they don't collide with the JSON-RPC stream.

use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};

#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
    let db_path = kon_storage::database_path();
    eprintln!(
        "[kon-mcp] opening Kon database at {}",
        db_path.display()
    );
    let pool = kon_storage::init(&db_path).await?;
    eprintln!("[kon-mcp] ready, waiting for JSON-RPC on stdin");

    let mut lines = BufReader::new(tokio::io::stdin()).lines();
    let mut stdout = tokio::io::stdout();

    while let Some(line) = lines.next_line().await? {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        let raw: serde_json::Value = match serde_json::from_str(trimmed) {
            Ok(value) => value,
            Err(err) => {
                eprintln!("[kon-mcp] ignoring malformed line: {err}");
                continue;
            }
        };

        let Some(response) = kon_mcp::handle_message(&pool, raw).await else {
            continue; // notification — no reply
        };

        let payload = serde_json::to_string(&response)?;
        stdout.write_all(payload.as_bytes()).await?;
        stdout.write_all(b"\n").await?;
        stdout.flush().await?;
    }

    Ok(())
}
