//! HTTP agent endpoints — thin adapters over `service::agents`.
//!
//! Each handler: extracts payload → calls `service::agents::X` → shapes
//! response DTO → returns HTTP result. No filesystem access, no inline
//! validation, no process invocations.
use crate::http::context::{AppContext, OpenApiResult, bad_request, not_found};
use crate::service::agents::{self as svc, AgentConfigEntry, WorkItemContent};
use crate::workflow::{StoryTestResults, TestCaseResult, TestStatus};
use poem::http::StatusCode;
use poem_openapi::{Object, OpenApi, Tags, param::Path, payload::Json};
use serde::Serialize;
use std::sync::Arc;

#[derive(Tags)]
enum AgentsTags {
    Agents,
}

#[derive(Object)]
struct StartAgentPayload {
    story_id: String,
    agent_name: Option<String>,
}

#[derive(Object)]
struct StopAgentPayload {
    story_id: String,
    agent_name: String,
}

#[derive(Object, Serialize)]
struct AgentInfoResponse {
    story_id: String,
    agent_name: String,
    status: String,
    session_id: Option<String>,
    worktree_path: Option<String>,
}

#[derive(Object, Serialize)]
struct AgentConfigInfoResponse {
    name: String,
    role: String,
    stage: Option<String>,
    model: Option<String>,
    allowed_tools: Option<Vec<String>>,
    max_turns: Option<u32>,
    max_budget_usd: Option<f64>,
}

impl From<AgentConfigEntry> for AgentConfigInfoResponse {
    fn from(e: AgentConfigEntry) -> Self {
        Self {
            name: e.name,
            role: e.role,
            stage: e.stage,
            model: e.model,
            allowed_tools: e.allowed_tools,
            max_turns: e.max_turns,
            max_budget_usd: e.max_budget_usd,
        }
    }
}

#[derive(Object)]
struct CreateWorktreePayload {
    story_id: String,
}

#[derive(Object, Serialize)]
struct WorktreeInfoResponse {
    story_id: String,
    worktree_path: String,
    branch: String,
    base_branch: String,
}

#[derive(Object, Serialize)]
struct WorktreeListEntry {
    story_id: String,
    path: String,
}

/// Response for the work item content endpoint.
#[derive(Object, Serialize)]
struct WorkItemContentResponse {
    content: String,
    stage: String,
    name: Option<String>,
    agent: Option<String>,
}

impl From<WorkItemContent> for WorkItemContentResponse {
    fn from(w: WorkItemContent) -> Self {
        Self {
            content: w.content,
            stage: w.stage,
            name: w.name,
            agent: w.agent,
        }
    }
}

/// A single test case result for the OpenAPI response.
#[derive(Object, Serialize)]
struct TestCaseResultResponse {
    name: String,
    status: String,
    details: Option<String>,
}

/// Response for the work item test results endpoint.
#[derive(Object, Serialize)]
struct TestResultsResponse {
    unit: Vec<TestCaseResultResponse>,
    integration: Vec<TestCaseResultResponse>,
}

impl TestResultsResponse {
    fn from_story_results(results: &StoryTestResults) -> Self {
        Self {
            unit: results.unit.iter().map(Self::map_case).collect(),
            integration: results.integration.iter().map(Self::map_case).collect(),
        }
    }

    fn map_case(tc: &TestCaseResult) -> TestCaseResultResponse {
        TestCaseResultResponse {
            name: tc.name.clone(),
            status: match tc.status {
                TestStatus::Pass => "pass".to_string(),
                TestStatus::Fail => "fail".to_string(),
            },
            details: tc.details.clone(),
        }
    }
}

/// Response for the agent output endpoint.
#[derive(Object, Serialize)]
struct AgentOutputResponse {
    output: String,
}

/// Per-agent cost breakdown entry for the token cost endpoint.
#[derive(Object, Serialize)]
struct AgentCostEntry {
    agent_name: String,
    model: Option<String>,
    input_tokens: u64,
    output_tokens: u64,
    cache_creation_input_tokens: u64,
    cache_read_input_tokens: u64,
    total_cost_usd: f64,
}

/// Response for the work item token cost endpoint.
#[derive(Object, Serialize)]
struct TokenCostResponse {
    total_cost_usd: f64,
    agents: Vec<AgentCostEntry>,
}

/// A single token usage record in the all-usage response.
#[derive(Object, Serialize)]
struct TokenUsageRecordResponse {
    story_id: String,
    agent_name: String,
    model: Option<String>,
    timestamp: String,
    input_tokens: u64,
    output_tokens: u64,
    cache_creation_input_tokens: u64,
    cache_read_input_tokens: u64,
    total_cost_usd: f64,
}

/// Response for the all token usage endpoint.
#[derive(Object, Serialize)]
struct AllTokenUsageResponse {
    records: Vec<TokenUsageRecordResponse>,
}

/// Map a `service::agents::Error` to a Poem HTTP error with the correct status.
fn map_svc_error(err: svc::Error) -> poem::Error {
    match err {
        svc::Error::AgentNotFound(_) => {
            poem::Error::from_string(err.to_string(), StatusCode::NOT_FOUND)
        }
        svc::Error::WorkItemNotFound(_) => {
            poem::Error::from_string(err.to_string(), StatusCode::NOT_FOUND)
        }
        svc::Error::Worktree(_) => {
            poem::Error::from_string(err.to_string(), StatusCode::BAD_REQUEST)
        }
        svc::Error::Config(_) => poem::Error::from_string(err.to_string(), StatusCode::BAD_REQUEST),
        svc::Error::Io(_) => {
            poem::Error::from_string(err.to_string(), StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

pub struct AgentsApi {
    pub ctx: Arc<AppContext>,
}

#[OpenApi(tag = "AgentsTags::Agents")]
impl AgentsApi {
    /// Start an agent for a given story (creates worktree, runs setup, spawns agent).
    /// If agent_name is omitted, the first configured agent is used.
    #[oai(path = "/agents/start", method = "post")]
    async fn start_agent(
        &self,
        payload: Json<StartAgentPayload>,
    ) -> OpenApiResult<Json<AgentInfoResponse>> {
        let project_root = self
            .ctx
            .services
            .agents
            .get_project_root(&self.ctx.state)
            .map_err(bad_request)?;

        let info = svc::start_agent(
            &self.ctx.services.agents,
            &project_root,
            &payload.0.story_id,
            payload.0.agent_name.as_deref(),
            None,
            None,
        )
        .await
        .map_err(map_svc_error)?;

        Ok(Json(AgentInfoResponse {
            story_id: info.story_id,
            agent_name: info.agent_name,
            status: info.status.to_string(),
            session_id: info.session_id,
            worktree_path: info.worktree_path,
        }))
    }

    /// Stop a running agent and clean up its worktree.
    #[oai(path = "/agents/stop", method = "post")]
    async fn stop_agent(&self, payload: Json<StopAgentPayload>) -> OpenApiResult<Json<bool>> {
        let project_root = self
            .ctx
            .services
            .agents
            .get_project_root(&self.ctx.state)
            .map_err(bad_request)?;

        svc::stop_agent(
            &self.ctx.services.agents,
            &project_root,
            &payload.0.story_id,
            &payload.0.agent_name,
        )
        .await
        .map_err(map_svc_error)?;

        Ok(Json(true))
    }

    /// List all agents with their status.
    ///
    /// Agents for stories that have been completed (`work/5_done/` or `work/6_archived/`) are
    /// excluded so the agents panel is not cluttered with old completed items
    /// on frontend startup.
    #[oai(path = "/agents", method = "get")]
    async fn list_agents(&self) -> OpenApiResult<Json<Vec<AgentInfoResponse>>> {
        let project_root = self
            .ctx
            .services
            .agents
            .get_project_root(&self.ctx.state)
            .ok();
        let agents = svc::list_agents(&self.ctx.services.agents, project_root.as_deref())
            .map_err(map_svc_error)?;

        Ok(Json(
            agents
                .into_iter()
                .map(|info| AgentInfoResponse {
                    story_id: info.story_id,
                    agent_name: info.agent_name,
                    status: info.status.to_string(),
                    session_id: info.session_id,
                    worktree_path: info.worktree_path,
                })
                .collect(),
        ))
    }

    /// Get the configured agent roster from project.toml.
    #[oai(path = "/agents/config", method = "get")]
    async fn get_agent_config(&self) -> OpenApiResult<Json<Vec<AgentConfigInfoResponse>>> {
        let project_root = self
            .ctx
            .services
            .agents
            .get_project_root(&self.ctx.state)
            .map_err(bad_request)?;

        let entries = svc::get_agent_config(&project_root).map_err(map_svc_error)?;
        Ok(Json(
            entries
                .into_iter()
                .map(AgentConfigInfoResponse::from)
                .collect(),
        ))
    }

    /// Reload project config and return the updated agent roster.
    #[oai(path = "/agents/config/reload", method = "post")]
    async fn reload_config(&self) -> OpenApiResult<Json<Vec<AgentConfigInfoResponse>>> {
        let project_root = self
            .ctx
            .services
            .agents
            .get_project_root(&self.ctx.state)
            .map_err(bad_request)?;

        let entries = svc::reload_config(&project_root).map_err(map_svc_error)?;
        Ok(Json(
            entries
                .into_iter()
                .map(AgentConfigInfoResponse::from)
                .collect(),
        ))
    }

    /// Create a git worktree for a story under .huskies/worktrees/{story_id}.
    #[oai(path = "/agents/worktrees", method = "post")]
    async fn create_worktree(
        &self,
        payload: Json<CreateWorktreePayload>,
    ) -> OpenApiResult<Json<WorktreeInfoResponse>> {
        let project_root = self
            .ctx
            .services
            .agents
            .get_project_root(&self.ctx.state)
            .map_err(bad_request)?;

        let info = svc::create_worktree(
            &self.ctx.services.agents,
            &project_root,
            &payload.0.story_id,
        )
        .await
        .map_err(map_svc_error)?;

        Ok(Json(WorktreeInfoResponse {
            story_id: payload.0.story_id,
            worktree_path: info.path.to_string_lossy().to_string(),
            branch: info.branch,
            base_branch: info.base_branch,
        }))
    }

    /// List all worktrees under .huskies/worktrees/.
    #[oai(path = "/agents/worktrees", method = "get")]
    async fn list_worktrees(&self) -> OpenApiResult<Json<Vec<WorktreeListEntry>>> {
        let project_root = self
            .ctx
            .services
            .agents
            .get_project_root(&self.ctx.state)
            .map_err(bad_request)?;

        let entries = svc::list_worktrees(&project_root).map_err(map_svc_error)?;

        Ok(Json(
            entries
                .into_iter()
                .map(|e| WorktreeListEntry {
                    story_id: e.story_id,
                    path: e.path.to_string_lossy().to_string(),
                })
                .collect(),
        ))
    }

    /// Get the markdown content of a work item by its story_id.
    ///
    /// Searches all active pipeline stages for the file and returns its content
    /// along with the stage it was found in.
    #[oai(path = "/work-items/:story_id", method = "get")]
    async fn get_work_item_content(
        &self,
        story_id: Path<String>,
    ) -> OpenApiResult<Json<WorkItemContentResponse>> {
        let project_root = self
            .ctx
            .services
            .agents
            .get_project_root(&self.ctx.state)
            .map_err(bad_request)?;

        let item = svc::get_work_item_content(&project_root, &story_id.0).map_err(|e| match e {
            svc::Error::WorkItemNotFound(_) => not_found(e.to_string()),
            other => map_svc_error(other),
        })?;

        Ok(Json(WorkItemContentResponse::from(item)))
    }

    /// Get test results for a work item by its story_id.
    ///
    /// Returns unit and integration test results. Checks in-memory workflow
    /// state first, then falls back to results persisted in the story file.
    #[oai(path = "/work-items/:story_id/test-results", method = "get")]
    async fn get_test_results(
        &self,
        story_id: Path<String>,
    ) -> OpenApiResult<Json<Option<TestResultsResponse>>> {
        // Fast path: return from in-memory state without requiring project_root.
        let in_memory = {
            let workflow = self
                .ctx
                .workflow
                .lock()
                .map_err(|e| bad_request(format!("Lock error: {e}")))?;
            workflow.results.get(&story_id.0).cloned()
        };
        if let Some(results) = in_memory {
            return Ok(Json(Some(TestResultsResponse::from_story_results(
                &results,
            ))));
        }

        // Slow path: fall back to results persisted in the story file.
        let project_root = self
            .ctx
            .services
            .agents
            .get_project_root(&self.ctx.state)
            .map_err(bad_request)?;

        let workflow = self
            .ctx
            .workflow
            .lock()
            .map_err(|e| bad_request(format!("Lock error: {e}")))?;

        let results = svc::get_test_results(&project_root, &story_id.0, &workflow);
        Ok(Json(
            results.map(|r| TestResultsResponse::from_story_results(&r)),
        ))
    }

    /// Get the historical output text for an agent session.
    ///
    /// Reads the most recent persistent log file for the given story+agent and
    /// returns all `output` events concatenated as a single string. Returns an
    /// empty string if no log file exists yet.
    #[oai(path = "/agents/:story_id/:agent_name/output", method = "get")]
    async fn get_agent_output(
        &self,
        story_id: Path<String>,
        agent_name: Path<String>,
    ) -> OpenApiResult<Json<AgentOutputResponse>> {
        let project_root = self
            .ctx
            .services
            .agents
            .get_project_root(&self.ctx.state)
            .map_err(bad_request)?;

        let output = svc::get_agent_output(&project_root, &story_id.0, &agent_name.0)
            .map_err(map_svc_error)?;

        Ok(Json(AgentOutputResponse { output }))
    }

    /// Remove a git worktree and its feature branch for a story.
    #[oai(path = "/agents/worktrees/:story_id", method = "delete")]
    async fn remove_worktree(&self, story_id: Path<String>) -> OpenApiResult<Json<bool>> {
        let project_root = self
            .ctx
            .services
            .agents
            .get_project_root(&self.ctx.state)
            .map_err(bad_request)?;

        svc::remove_worktree(&project_root, &story_id.0)
            .await
            .map_err(map_svc_error)?;

        Ok(Json(true))
    }

    /// Get the total token cost and per-agent breakdown for a work item.
    ///
    /// Returns the sum of all recorded token usage for the given story_id.
    /// If no usage has been recorded, returns zero cost with an empty agents list.
    #[oai(path = "/work-items/:story_id/token-cost", method = "get")]
    async fn get_work_item_token_cost(
        &self,
        story_id: Path<String>,
    ) -> OpenApiResult<Json<TokenCostResponse>> {
        let project_root = self
            .ctx
            .services
            .agents
            .get_project_root(&self.ctx.state)
            .map_err(bad_request)?;

        let summary =
            svc::get_work_item_token_cost(&project_root, &story_id.0).map_err(map_svc_error)?;

        let agents = summary
            .agents
            .into_iter()
            .map(|a| AgentCostEntry {
                agent_name: a.agent_name,
                model: a.model,
                input_tokens: a.input_tokens,
                output_tokens: a.output_tokens,
                cache_creation_input_tokens: a.cache_creation_input_tokens,
                cache_read_input_tokens: a.cache_read_input_tokens,
                total_cost_usd: a.total_cost_usd,
            })
            .collect();

        Ok(Json(TokenCostResponse {
            total_cost_usd: summary.total_cost_usd,
            agents,
        }))
    }

    /// Get all token usage records across all stories.
    ///
    /// Returns the full history from the persistent token_usage.jsonl log.
    #[oai(path = "/token-usage", method = "get")]
    async fn get_all_token_usage(&self) -> OpenApiResult<Json<AllTokenUsageResponse>> {
        let project_root = self
            .ctx
            .services
            .agents
            .get_project_root(&self.ctx.state)
            .map_err(bad_request)?;

        let records = svc::get_all_token_usage(&project_root).map_err(map_svc_error)?;

        let response_records: Vec<TokenUsageRecordResponse> = records
            .into_iter()
            .map(|r| TokenUsageRecordResponse {
                story_id: r.story_id,
                agent_name: r.agent_name,
                model: r.model,
                timestamp: r.timestamp,
                input_tokens: r.usage.input_tokens,
                output_tokens: r.usage.output_tokens,
                cache_creation_input_tokens: r.usage.cache_creation_input_tokens,
                cache_read_input_tokens: r.usage.cache_read_input_tokens,
                total_cost_usd: r.usage.total_cost_usd,
            })
            .collect();

        Ok(Json(AllTokenUsageResponse {
            records: response_records,
        }))
    }
}

#[cfg(test)]
mod tests;
