/**
 * A2P AutoPilot MCP Tool Handlers
 * Executes tool requests, calls the A2P AutoPilot API, returns structured content
 */

import type { SubmissionRecord, RegistrationInput } from '../../src/types.js';
import {
  mockSubmissions,
  mockStats,
  getMockSubmission,
  getMockSubmissionsByStatus
} from './mock-data.js';

const API_BASE_URL = process.env.A2P_API_URL || 'http://localhost:3100';
const USE_MOCK_DATA = process.env.USE_MOCK_DATA === 'true' || true; // Default to mock for now

// ============================================================
// API HELPERS
// ============================================================

async function callAPI<T>(endpoint: string, options?: RequestInit): Promise<T> {
  if (USE_MOCK_DATA) {
    // Return mock data based on endpoint
    return handleMockAPI(endpoint, options) as T;
  }

  try {
    const response = await fetch(`${API_BASE_URL}${endpoint}`, {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        ...options?.headers
      }
    });

    if (!response.ok) {
      throw new Error(`API error: ${response.status} ${response.statusText}`);
    }

    return await response.json();
  } catch (error) {
    console.error(`API call failed for ${endpoint}:`, error);
    throw error;
  }
}

function handleMockAPI(endpoint: string, options?: RequestInit): any {
  const method = options?.method || 'GET';
  
  if (endpoint === '/submissions' && method === 'GET') {
    return { submissions: mockSubmissions };
  }
  
  if (endpoint.startsWith('/submissions/') && method === 'GET') {
    const id = endpoint.split('/')[2];
    return getMockSubmission(id);
  }
  
  if (endpoint === '/submissions' && method === 'POST') {
    const body = JSON.parse(options?.body as string);
    return {
      id: `sub_${Date.now()}`,
      input: body,
      status: 'pending',
      sidChain: {},
      remediationHistory: [],
      attemptCount: 0,
      maxAttempts: 3,
      createdAt: new Date(),
      updatedAt: new Date()
    };
  }
  
  if (endpoint.endsWith('/retry') && method === 'POST') {
    return { success: true, message: 'Retry initiated' };
  }
  
  if (endpoint.endsWith('/cancel') && method === 'POST') {
    return { success: true, message: 'Submission cancelled' };
  }
  
  if (endpoint.endsWith('/status') && method === 'GET') {
    const id = endpoint.split('/')[2];
    return getMockSubmission(id);
  }
  
  if (endpoint === '/stats' && method === 'GET') {
    return mockStats;
  }
  
  return null;
}

// ============================================================
// TOOL HANDLERS
// ============================================================

export async function handleRegistrationWizard(args: { externalId?: string }) {
  // For UI tools, we return structured content with the data the UI needs
  let prefillData = null;
  
  if (args.externalId) {
    // Try to find existing submission by externalId
    const existing = mockSubmissions.find(
      sub => sub.input.externalId === args.externalId
    );
    if (existing) {
      prefillData = existing.input;
    }
  }
  
  return {
    content: [
      {
        type: 'resource',
        resource: {
          uri: 'ui://a2p/registration-wizard',
          mimeType: 'text/html'
        }
      }
    ],
    structuredContent: {
      prefillData,
      externalId: args.externalId
    }
  };
}

export async function handleDashboard(args: { status?: string }) {
  const submissions = args.status
    ? getMockSubmissionsByStatus(args.status as any)
    : mockSubmissions;
  
  return {
    content: [
      {
        type: 'resource',
        resource: {
          uri: 'ui://a2p/dashboard',
          mimeType: 'text/html'
        }
      }
    ],
    structuredContent: {
      submissions,
      stats: mockStats,
      filterStatus: args.status
    }
  };
}

export async function handleViewSubmission(args: { submissionId: string }) {
  const submission = getMockSubmission(args.submissionId);
  
  if (!submission) {
    throw new Error(`Submission not found: ${args.submissionId}`);
  }
  
  return {
    content: [
      {
        type: 'resource',
        resource: {
          uri: 'ui://a2p/submission-detail',
          mimeType: 'text/html'
        }
      }
    ],
    structuredContent: {
      submission
    }
  };
}

export async function handlePreviewLanding(args: { submissionId: string }) {
  const submission = getMockSubmission(args.submissionId);
  
  if (!submission) {
    throw new Error(`Submission not found: ${args.submissionId}`);
  }
  
  return {
    content: [
      {
        type: 'resource',
        resource: {
          uri: 'ui://a2p/landing-preview',
          mimeType: 'text/html'
        }
      }
    ],
    structuredContent: {
      submission,
      landingPageUrl: submission.landingPageUrl || `https://a2p.example.com/${args.submissionId}/landing`,
      privacyPolicyUrl: submission.privacyPolicyUrl || `https://a2p.example.com/${args.submissionId}/privacy`,
      termsUrl: submission.termsUrl || `https://a2p.example.com/${args.submissionId}/terms`
    }
  };
}

export async function handleSubmitRegistration(args: RegistrationInput) {
  const result = await callAPI<SubmissionRecord>('/submissions', {
    method: 'POST',
    body: JSON.stringify(args)
  });
  
  return {
    content: [
      {
        type: 'text',
        text: `Registration submitted successfully. Submission ID: ${result.id}`
      }
    ],
    structuredContent: {
      submissionId: result.id,
      status: result.status,
      submission: result
    }
  };
}

export async function handleRetrySubmission(args: { submissionId: string }) {
  const result = await callAPI<{ success: boolean; message: string }>(
    `/submissions/${args.submissionId}/retry`,
    { method: 'POST' }
  );
  
  return {
    content: [
      {
        type: 'text',
        text: result.message
      }
    ],
    structuredContent: {
      success: result.success,
      submissionId: args.submissionId
    }
  };
}

export async function handleCancelSubmission(args: { submissionId: string }) {
  const result = await callAPI<{ success: boolean; message: string }>(
    `/submissions/${args.submissionId}/cancel`,
    { method: 'POST' }
  );
  
  return {
    content: [
      {
        type: 'text',
        text: result.message
      }
    ],
    structuredContent: {
      success: result.success,
      submissionId: args.submissionId
    }
  };
}

export async function handleCheckStatus(args: { submissionId: string }) {
  const submission = await callAPI<SubmissionRecord>(
    `/submissions/${args.submissionId}/status`
  );
  
  return {
    content: [
      {
        type: 'text',
        text: `Submission ${args.submissionId} status: ${submission.status}`
      }
    ],
    structuredContent: {
      submission,
      status: submission.status
    }
  };
}

export async function handleGetStats() {
  const stats = await callAPI<typeof mockStats>('/stats');
  
  return {
    content: [
      {
        type: 'text',
        text: `Total submissions: ${stats.total}, Success rate: ${stats.successRate}%`
      }
    ],
    structuredContent: {
      stats
    }
  };
}
