import type { RuntimeMode, TargetMetricsResponse } from "../../shared/api";
import type { ProbeStore } from "../checker/store";

import { jsonResponse } from "../helpers";
import {
  analyzeIncidentSequence,
  buildHourlyTrend,
  calculateAverageDuration,
  calculateCurrentStreak,
  calculatePercentile,
  type MetricCheckpoint,
} from "../metrics";
import { validateMetricsBucket, validateTargetId, validateTimeRange } from "../middleware";

export function handleMetrics(idStr: string, url: URL, store: ProbeStore, mode: RuntimeMode): Response {
  const idResult = validateTargetId(idStr, mode);
  if (idResult instanceof Response) return idResult;

  const target = store.getTargetById(idResult.id);
  if (!target) {
    return jsonResponse({ error: "Target not found", status: 404 } as const, { mode, status: 404 });
  }

  const timeResult = validateTimeRange(url.searchParams.get("from"), url.searchParams.get("to"), mode);
  if (timeResult instanceof Response) return timeResult;

  const bucketResult = validateMetricsBucket(url.searchParams.get("bucket"), mode);
  if (bucketResult instanceof Response) return bucketResult;

  const checkpoints = store
    .getTargetCheckpoints(idResult.id, timeResult.from, timeResult.to)
    .map((checkpoint): MetricCheckpoint => {
      return {
        durationMs: checkpoint.duration_ms,
        matched: checkpoint.matched === 1,
        timestamp: checkpoint.timestamp,
      };
    });
  const durations = store.getTargetDurations(idResult.id, timeResult.from, timeResult.to);
  const stats = store.getTargetWindowStats(idResult.id, timeResult.from, timeResult.to);
  const incidentAnalysis = analyzeIncidentSequence(checkpoints, timeResult.from, timeResult.to);

  const response: TargetMetricsResponse = {
    stats: {
      availability: stats.availability,
      avgDurationMs: calculateAverageDuration(durations),
      currentStreak: calculateCurrentStreak(checkpoints),
      downChecks: stats.downChecks,
      incidentCount: incidentAnalysis.incidentCount,
      longestOutage: incidentAnalysis.longestOutage,
      mttr: incidentAnalysis.mttr,
      p95DurationMs: calculatePercentile(durations, 95),
      p99DurationMs: calculatePercentile(durations, 99),
      totalChecks: stats.totalChecks,
      upChecks: stats.upChecks,
    },
    targetId: idResult.id,
    trend: buildHourlyTrend(checkpoints),
    window: {
      bucket: bucketResult.bucket,
      from: timeResult.from,
      to: timeResult.to,
    },
  };

  return jsonResponse(response, { mode });
}
