import type { CommitMessageResult } from "../commands/commit/types";
import { parseJsonResponse } from "./response-cleaner";

export class ResponseParser {
  static parseCommitMessage(response: string): CommitMessageResult {
    // Try to parse as JSON using the utility
    const parsed = parseJsonResponse<any>(response);
    
    // Validate the structure if JSON was successfully parsed
    if (parsed && parsed.type && parsed.subject) {
      return {
        type: parsed.type,
        scope: parsed.scope || undefined,
        emoji: parsed.emoji || undefined,
        subject: parsed.subject,
        body: parsed.body || undefined,
      };
    }
    
    // Fallback: Parse plain text response
    return this.parseCommitMessageFromText(response);
  }
  
  private static parseCommitMessageFromText(text: string): CommitMessageResult {
    const lines = text.trim().split('\n').filter(line => line.trim());
    
    if (lines.length === 0) {
      throw new Error("Empty response from AI provider");
    }
    
    const firstLine = lines[0]?.trim() || "";
    
    // Simple parsing - just return the text as a feat commit
    return {
      type: "feat",
      subject: firstLine,
      body: lines.slice(1).join('\n').trim() || undefined,
    };
  }
  
  static formatCommitMessage(result: CommitMessageResult): string {
    let message = "";
    
    // Add emoji if present
    if (result.emoji) {
      message += `${result.emoji} `;
    }
    
    // Add type and scope
    message += result.type;
    if (result.scope) {
      message += `(${result.scope})`;
    }
    message += `: ${result.subject}`;
    
    // Add body if present
    if (result.body) {
      message += `\n\n${result.body}`;
    }
    
    return message;
  }
}