import { color } from "@/utils/formatter";
import { parseJsonResponse } from "@/utils/response-cleaner";
import type { ReviewResult } from "@/commands/review/types";

/**
 * Parse JSON response from AI provider into ReviewResult
 */
export function parseReviewResponse(response: string): ReviewResult | null {
  // Use the utility to parse JSON with automatic code block cleaning
  const parsed = parseJsonResponse<any>(response);
  
  // Validate required fields
  if (parsed && parsed.summary && Array.isArray(parsed.issues)) {
    // Ensure optional array fields are actually arrays or undefined
    const result: ReviewResult = {
      summary: parsed.summary,
      issues: parsed.issues,
      score: parsed.score,
      recommendations: Array.isArray(parsed.recommendations) ? parsed.recommendations : undefined,
      positives: Array.isArray(parsed.positives) ? parsed.positives : undefined,
    };
    return result;
  }
  
  // If not valid structure or parsing failed, return null
  return null;
}

/**
 * Format review result for text output
 */
export function formatReviewAsText(review: ReviewResult): string {
  const lines: string[] = [];
  
  // Header
  lines.push(color("📝 Code Review", "cyan"));
  lines.push(color("═".repeat(60), "gray"));
  lines.push("");
  
  // Summary
  lines.push(color("Summary:", "yellow"));
  lines.push(review.summary);
  lines.push("");
  
  // Issues
  if (review.issues && review.issues.length > 0) {
    lines.push(color(`Issues Found (${review.issues.length}):`, "yellow"));
    lines.push(color("─".repeat(40), "gray"));
    
    review.issues.forEach((issue, index) => {
      const icon = getSeverityIcon(issue.severity);
      const severityColor = getSeverityColor(issue.severity);
      
      lines.push("");
      lines.push(`${index + 1}. ${icon} ${color(issue.severity.toUpperCase(), severityColor)}`);
      
      if (issue.file) {
        const location = issue.line ? `${issue.file}:${issue.line}` : issue.file;
        lines.push(`   ${color("File:", "gray")} ${location}`);
      }
      
      lines.push(`   ${color("Issue:", "gray")} ${issue.message}`);
      
      if (issue.suggestion) {
        lines.push(`   ${color("Suggestion:", "green")} ${issue.suggestion}`);
      }
    });
  } else {
    lines.push(color("✅ No issues found!", "green"));
  }
  
  lines.push("");
  
  // Positive aspects
  if (review.positives && Array.isArray(review.positives) && review.positives.length > 0) {
    lines.push(color("Positive Aspects:", "green"));
    lines.push(color("─".repeat(40), "gray"));
    review.positives.forEach(positive => {
      lines.push(`  ✅ ${positive}`);
    });
    lines.push("");
  }
  
  // Recommendations
  if (review.recommendations && Array.isArray(review.recommendations) && review.recommendations.length > 0) {
    lines.push(color("Recommendations:", "blue"));
    lines.push(color("─".repeat(40), "gray"));
    review.recommendations.forEach(rec => {
      lines.push(`  💡 ${rec}`);
    });
    lines.push("");
  }
  
  // Score
  if (review.score !== undefined) {
    // Color thresholds: 8+ is green (good), 6-7 is yellow (moderate), <6 is red (needs improvement)
    const scoreColor = review.score >= 8 ? "green" : review.score >= 6 ? "yellow" : "red";
    lines.push(color("─".repeat(40), "gray"));
    lines.push(color(`Overall Score: ${review.score}/10`, scoreColor));
  }
  
  return lines.join("\n");
}

/**
 * Format review result for GitHub Actions output
 */
export function formatReviewAsGitHub(review: ReviewResult): string {
  const lines: string[] = [];
  
  // Output GitHub Actions annotations for issues
  if (review.issues && review.issues.length > 0) {
    review.issues.forEach(issue => {
      const level = mapSeverityToGitHubLevel(issue.severity);
      let annotation = `::${level}`;
      
      if (issue.file) {
        annotation += ` file=${issue.file}`;
        if (issue.line) {
          annotation += `,line=${issue.line}`;
        }
      }
      
      annotation += `::${escapeGitHubAnnotation(issue.message)}`;
      lines.push(annotation);
    });
  }
  
  // Output summary as markdown comment
  lines.push("");
  lines.push("## 📝 Code Review Summary");
  lines.push("");
  lines.push(review.summary);
  
  if (review.score !== undefined) {
    lines.push("");
    lines.push(`**Score:** ${review.score}/10`);
  }
  
  return lines.join("\n");
}

/**
 * Format review result as JSON
 */
export function formatReviewAsJson(review: ReviewResult): string {
  return JSON.stringify({
    status: "success",
    data: review,
    timestamp: new Date().toISOString()
  }, null, 2);
}

function getSeverityIcon(severity: string): string {
  switch (severity) {
    case "error":
      return "🔴";
    case "warning":
      return "🟡";
    case "info":
      return "🔵";
    default:
      return "⚪";
  }
}

function getSeverityColor(severity: string): "red" | "yellow" | "blue" | "gray" {
  switch (severity) {
    case "error":
      return "red";
    case "warning":
      return "yellow";
    case "info":
      return "blue";
    default:
      return "gray";
  }
}

function mapSeverityToGitHubLevel(severity: string): string {
  switch (severity) {
    case "error":
      return "error";
    case "warning":
      return "warning";
    case "info":
    default:
      return "notice";
  }
}

function escapeGitHubAnnotation(text: string): string {
  return text
    .replace(/%/g, "%25")
    .replace(/\r/g, "%0D")
    .replace(/\n/g, "%0A");
}