pub mod agent;
pub mod compat;
pub mod config;
pub mod llm;
pub mod pipe;
pub mod security;

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use agent::handle_browser_message;
use pipe::{perform_handshake, BrowserPipeTool, PipeError, StdioTransport, Transport};
use security::MacPolicy;

fn default_rules_path() -> PathBuf {
    std::env::current_dir()
        .unwrap_or_else(|_| PathBuf::from("."))
        .join("resources")
        .join("rules.json")
}

pub fn run() -> Result<(), PipeError> {
    let transport = Arc::new(StdioTransport::new(std::io::stdin(), std::io::stdout()));
    let handshake = perform_handshake(transport.as_ref(), Duration::from_secs(5))?;
    let mac_policy = MacPolicy::load_from_path(default_rules_path())?;
    let browser_tool = BrowserPipeTool::new(transport.clone(), mac_policy, handshake.session_key)
        .with_response_timeout(Duration::from_secs(30));

    eprintln!("sgclaw ready: agent_id={}", handshake.agent_id);

    loop {
        match transport.recv_timeout(Duration::from_secs(3600)) {
            Ok(message) => {
                handle_browser_message(transport.as_ref(), &browser_tool, message)?;
            }
            Err(PipeError::Timeout) => continue,
            Err(PipeError::PipeClosed) => return Ok(()),
            Err(err) => return Err(err),
        }
    }
}
