import { z } from 'zod';

const ReportSchema = z.object({
  status: z.enum(['completed', 'blocked', 'insufficient_context', 'failed'])
    .describe('Final execution status'),

  summary: z.string()
    .describe('1-2 sentence human-readable summary of what was analyzed/implemented'),

  storyPoints: z.object({
    points: z.number(),
    confidence: z.enum(['high', 'medium', 'low'])
  }).optional()
    .describe('Story point estimate from analysis'),

  complexity: z.enum(['simple', 'medium', 'complex', 'unknown']).optional()
    .describe('Implementation complexity from analysis'),

  codeMetrics: z.object({
    filesChanged: z.number(),
    additions: z.number(),
    deletions: z.number(),
    netChange: z.number()
  }).optional()
    .describe('Code change metrics (only present when code was generated)'),

  testCount: z.number().optional()
    .describe('Number of test cases generated'),

  risks: z.array(z.string()).optional()
    .describe('Potential risks or challenges identified during analysis'),

  blockers: z.array(z.string()).optional()
    .describe('Blockers preventing implementation (when status is blocked/insufficient_context)')
});

const FinalizeOutputSchema = z.object({
  success: z.boolean(),
  report: ReportSchema
});

export const finalizeNode = {
  name: 'finalize',
  outputSchema: FinalizeOutputSchema,

  execute: async (state) => {
    console.log('\n📝 Finalizing...');

    const { ticketContext } = state;

    const analysis = state.analysis;
    const codeImpl = state.codeImplementation;
    const tests = state.tests;

    const structured = analysis?.structured;
    const validation = structured?.validation;

    let status = 'completed';
    let blockers;
    if (validation && !validation.canProceed) {
      status = validation.status === 'insufficient_context'
        ? 'insufficient_context'
        : 'blocked';
      blockers = validation.blockers;
    }

    const testCases = tests?.structured?.testCases || tests?.cases || [];

    const report = {
      status,
      summary: structured?.overallSummary || ticketContext.summary || `Analysis for ${ticketContext.ticketKey}`,

      ...(structured?.storyPointEstimate && {
        storyPoints: {
          points: structured.storyPointEstimate.points,
          confidence: structured.storyPointEstimate.confidence
        }
      }),

      ...(structured?.technicalAnalysis?.complexity && {
        complexity: structured.technicalAnalysis.complexity
      }),

      ...(codeImpl?.metrics && {
        codeMetrics: {
          filesChanged: codeImpl.metrics.filesChanged,
          additions: codeImpl.metrics.additions,
          deletions: codeImpl.metrics.deletions,
          netChange: codeImpl.metrics.netChange
        }
      }),

      ...(testCases.length > 0 && { testCount: testCases.length }),

      ...(structured?.technicalAnalysis?.risks?.length > 0 && {
        risks: structured.technicalAnalysis.risks
      }),

      ...(blockers?.length > 0 && { blockers })
    };

    console.log(`\n${  '='.repeat(60)}`);
    console.log('FINALIZE SUMMARY');
    console.log('='.repeat(60));
    console.log(JSON.stringify(report, null, 2));
    console.log('='.repeat(60));

    if (status !== 'completed') {
      console.log(`\n⚠️  Execution blocked: ${status}`);
      if (validation?.reasoning) console.log(`   Reason: ${validation.reasoning}`);
    }

    return {
      success: true,
      report
    };
  }
};
