// ═══════════════════════════════════════════════════════════
// Resources: pipeline state, test results, build logs
// ═══════════════════════════════════════════════════════════

import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import * as api from "../api-client.js";

export function registerPipelineResources(server: McpServer): void {
  // ───────────────────────────────────────
  // factory://pipelines/{pipeline_id}/state
  // ───────────────────────────────────────
  server.resource(
    "pipeline-state",
    new ResourceTemplate("factory://pipelines/{pipeline_id}/state", {
      list: undefined,
    }),
    {
      description: "Current state of a specific pipeline including stage, progress, tasks, and blockers",
      mimeType: "application/json",
    },
    async (uri, params) => {
      const pipelineId = params.pipeline_id as string;
      try {
        const [pipeline, stages, tasks] = await Promise.all([
          api.getPipeline(pipelineId),
          api.getPipelineStages(pipelineId).catch(() => []),
          api.listTasks({ pipelineId, limit: 50 }).catch(() => []),
        ]);

        let blockers: Awaited<ReturnType<typeof api.getBlockers>> = [];
        try {
          blockers = await api.getBlockers(pipelineId);
        } catch { /* optional */ }

        const state = {
          pipeline,
          stages,
          currentTasks: tasks,
          recentAssets: [],
          blockers,
          timeline: [],
        };

        return {
          contents: [
            {
              uri: uri.href,
              mimeType: "application/json" as const,
              text: JSON.stringify(state, null, 2),
            },
          ],
        };
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return {
          contents: [
            {
              uri: uri.href,
              mimeType: "application/json" as const,
              text: JSON.stringify({ error: msg }, null, 2),
            },
          ],
        };
      }
    },
  );

  // ───────────────────────────────────────
  // factory://servers/{server_name}/status
  // ───────────────────────────────────────
  server.resource(
    "server-status",
    new ResourceTemplate("factory://servers/{server_name}/status", {
      list: undefined,
    }),
    {
      description: "Health, version, deployment status of a specific MCP server",
      mimeType: "application/json",
    },
    async (uri, params) => {
      const serverName = params.server_name as string;
      try {
        // Search for the pipeline by server name
        const pipelines = await api.listPipelines({ search: serverName, limit: 1 });

        if (pipelines.length === 0) {
          return {
            contents: [
              {
                uri: uri.href,
                mimeType: "application/json" as const,
                text: JSON.stringify(
                  { error: `Server "${serverName}" not found`, name: serverName, health: "unknown" },
                  null,
                  2,
                ),
              },
            ],
          };
        }

        const pipeline = pipelines[0];
        const status = {
          name: serverName,
          pipelineId: pipeline.id,
          stage: pipeline.currentStage,
          health:
            pipeline.status === "active"
              ? "healthy"
              : pipeline.status === "failed"
                ? "failing"
                : "unknown",
          deployments: {
            staging: null,
            production: null,
          },
          lastTestRun: null,
          metrics: {},
        };

        return {
          contents: [
            {
              uri: uri.href,
              mimeType: "application/json" as const,
              text: JSON.stringify(status, null, 2),
            },
          ],
        };
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return {
          contents: [
            {
              uri: uri.href,
              mimeType: "application/json" as const,
              text: JSON.stringify({ error: msg, name: serverName }, null, 2),
            },
          ],
        };
      }
    },
  );

  // ───────────────────────────────────────
  // factory://pipelines/{pipeline_id}/test-results
  // ───────────────────────────────────────
  server.resource(
    "pipeline-test-results",
    new ResourceTemplate("factory://pipelines/{pipeline_id}/test-results", {
      list: undefined,
    }),
    {
      description: "Latest test results with pass/fail counts, coverage, and failure details",
      mimeType: "application/json",
    },
    async (uri, params) => {
      const pipelineId = params.pipeline_id as string;
      try {
        // Fetch pipeline and look for test results in tasks context
        const tasks = await api.listTasks({ pipelineId, limit: 50 });
        const testTask = tasks.find(
          (t) => t.context?.testResults || t.type === "review",
        );

        const results = testTask?.context?.testResults || {
          total: 0,
          passed: 0,
          failed: 0,
          skipped: 0,
          coveragePercent: 0,
          failureDetails: [],
        };

        return {
          contents: [
            {
              uri: uri.href,
              mimeType: "application/json" as const,
              text: JSON.stringify(results, null, 2),
            },
          ],
        };
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return {
          contents: [
            {
              uri: uri.href,
              mimeType: "application/json" as const,
              text: JSON.stringify({ error: msg }, null, 2),
            },
          ],
        };
      }
    },
  );

  // ───────────────────────────────────────
  // factory://pipelines/{pipeline_id}/build-logs
  // ───────────────────────────────────────
  server.resource(
    "pipeline-build-logs",
    new ResourceTemplate("factory://pipelines/{pipeline_id}/build-logs", {
      list: undefined,
    }),
    {
      description: "Build output logs for the latest build of a pipeline",
      mimeType: "text/plain",
    },
    async (uri, params) => {
      const pipelineId = params.pipeline_id as string;
      try {
        // In a full implementation, this would fetch from the build system
        // For now, construct from audit log
        const auditEntries = await api.getAuditLog({
          entityType: "pipeline",
          entityId: pipelineId,
          limit: 50,
        });

        const logLines = auditEntries
          .map((e) => `[${e.createdAt}] ${e.action} by ${e.actorName || e.actorType}`)
          .join("\n");

        return {
          contents: [
            {
              uri: uri.href,
              mimeType: "text/plain" as const,
              text: logLines || `No build logs available for pipeline ${pipelineId}`,
            },
          ],
        };
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return {
          contents: [
            {
              uri: uri.href,
              mimeType: "text/plain" as const,
              text: `Error fetching build logs: ${msg}`,
            },
          ],
        };
      }
    },
  );
}
