mod common;

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

use common::MockTransport;
use sgclaw::agent::handle_browser_message;
use sgclaw::pipe::{AgentMessage, BrowserMessage, BrowserPipeTool};
use sgclaw::security::MacPolicy;

fn test_policy() -> MacPolicy {
    MacPolicy::from_json_str(
        r#"{
            "version": "1.0",
            "domains": { "allowed": ["oa.example.com", "www.baidu.com"] },
            "pipe_actions": {
                "allowed": ["click", "type", "navigate", "getText"],
                "blocked": ["eval", "executeJsInPage"]
            }
        }"#,
    )
    .unwrap()
}

#[test]
fn submit_task_without_llm_configuration_returns_clear_error() {
    let transport = Arc::new(MockTransport::new(vec![]));
    let tool = BrowserPipeTool::new(
        transport.clone(),
        test_policy(),
        vec![1, 2, 3, 4, 5, 6, 7, 8],
    )
    .with_response_timeout(Duration::from_secs(1));

    handle_browser_message(
        transport.as_ref(),
        &tool,
        BrowserMessage::SubmitTask {
            instruction: "打开百度搜索天气".to_string(),
            conversation_id: String::new(),
            messages: vec![],
            page_url: String::new(),
            page_title: String::new(),
        },
    )
    .unwrap();

    let sent = transport.sent_messages();

    assert_eq!(sent.len(), 2);
    assert!(matches!(
        &sent[0],
        AgentMessage::LogEntry { level, message }
            if level == "info"
                && message.starts_with("sgclaw runtime version=")
                && message.ends_with(" protocol=1.0")
    ));
    assert!(matches!(
        &sent[1],
        AgentMessage::TaskComplete { success, summary }
            if !success && summary.contains("未配置大语言模型")
    ));
}
