import { ProcessDefinition, PersonaType } from './types.js';

export interface ProcessTemplate {
  id: string;
  name: string;
  description: string;
  persona?: PersonaType;
  category: 'development' | 'business' | 'operations' | 'customer';
  variables: Record<string, any>;
  processDefinition: Omit<ProcessDefinition, 'id' | 'metadata'>;
}

export const processTemplates: ProcessTemplate[] = [
  {
    id: 'daily-standup',
    name: 'Daily Standup Automation',
    description: 'Collect and share daily standup notes from team members',
    persona: 'software-engineer',
    category: 'development',
    variables: {
      teamName: 'Engineering',
      standupTime: '10:00',
      slackChannel: '#standup'
    },
    processDefinition: {
      name: 'Daily Standup - ${teamName}',
      description: 'Automated daily standup collection and distribution',
      version: '1.0.0',
      triggers: [
        {
          id: 'daily-trigger',
          type: 'schedule',
          name: 'Daily at ${standupTime}',
          enabled: true,
          config: {
            cron: '0 10 * * 1-5' // Weekdays at 10 AM
          }
        }
      ],
      activities: [
        {
          id: 'collect-updates',
          type: 'tool',
          name: 'Collect Team Updates',
          config: {
            toolName: 'daily_standup',
            toolArgs: {
              team: '${teamName}'
            }
          }
        },
        {
          id: 'format-report',
          type: 'tool',
          name: 'Format Standup Report',
          config: {
            toolName: 'generate_report',
            toolArgs: {
              type: 'standup',
              data: '${activityResults.collect-updates}'
            }
          }
        },
        {
          id: 'send-to-slack',
          type: 'external',
          name: 'Post to Slack',
          config: {
            url: 'https://slack.com/api/chat.postMessage',
            method: 'POST',
            headers: {
              'Authorization': 'Bearer ${slackToken}',
              'Content-Type': 'application/json'
            },
            body: {
              channel: '${slackChannel}',
              text: '${activityResults.format-report.content}'
            }
          }
        }
      ],
      variables: {
        teamName: 'Engineering',
        standupTime: '10:00',
        slackChannel: '#standup'
      }
    }
  },
  
  {
    id: 'weekly-report',
    name: 'Weekly Development Report',
    description: 'Generate and send comprehensive weekly development reports',
    persona: 'software-engineer',
    category: 'development',
    variables: {
      reportDay: 'Friday',
      reportTime: '17:00',
      recipients: ['team@company.com']
    },
    processDefinition: {
      name: 'Weekly Development Report',
      description: 'Automated weekly progress reporting',
      version: '1.0.0',
      triggers: [
        {
          id: 'weekly-trigger',
          type: 'schedule',
          name: 'Every ${reportDay} at ${reportTime}',
          enabled: true,
          config: {
            cron: '0 17 * * 5' // Friday at 5 PM
          }
        }
      ],
      activities: [
        {
          id: 'git-stats',
          type: 'tool',
          name: 'Collect Git Statistics',
          config: {
            toolName: 'get_git_stats',
            toolArgs: {}
          }
        },
        {
          id: 'sprint-status',
          type: 'tool',
          name: 'Get Sprint Status',
          config: {
            toolName: 'get_sprint_status',
            toolArgs: {}
          }
        },
        {
          id: 'completed-tasks',
          type: 'tool',
          name: 'Get Completed Tasks',
          config: {
            toolName: 'list_backlog',
            toolArgs: {
              status: 'done',
              days: 7
            }
          }
        },
        {
          id: 'generate-report',
          type: 'tool',
          name: 'Generate Weekly Report',
          config: {
            toolName: 'generate_report',
            toolArgs: {
              type: 'weekly',
              gitStats: '${activityResults.git-stats}',
              sprintStatus: '${activityResults.sprint-status}',
              completedTasks: '${activityResults.completed-tasks}'
            }
          }
        },
        {
          id: 'send-email',
          type: 'external',
          name: 'Send Email Report',
          config: {
            url: 'https://api.sendgrid.com/v3/mail/send',
            method: 'POST',
            headers: {
              'Authorization': 'Bearer ${sendgridApiKey}',
              'Content-Type': 'application/json'
            },
            body: {
              personalizations: [{
                to: '${recipients}'
              }],
              from: { email: 'reports@company.com' },
              subject: 'Weekly Development Report - Week ${weekNumber}',
              content: [{
                type: 'text/html',
                value: '${activityResults.generate-report.html}'
              }]
            }
          }
        }
      ],
      variables: {
        reportDay: 'Friday',
        reportTime: '17:00',
        recipients: ['team@company.com']
      }
    }
  },
  
  {
    id: 'code-review',
    name: 'Automated Code Review',
    description: 'Perform automated code review on pull requests',
    persona: 'software-engineer',
    category: 'development',
    variables: {
      minCoverage: 80,
      minQualityScore: 75
    },
    processDefinition: {
      name: 'Automated Code Review',
      description: 'Quality gates for pull requests',
      version: '1.0.0',
      triggers: [
        {
          id: 'pr-trigger',
          type: 'event',
          name: 'On Pull Request',
          enabled: true,
          config: {
            event: 'pull_request_opened'
          }
        }
      ],
      activities: [
        {
          id: 'run-tests',
          type: 'tool',
          name: 'Run Test Suite',
          config: {
            toolName: 'run_tests',
            toolArgs: {
              coverage: true
            }
          }
        },
        {
          id: 'check-coverage',
          type: 'tool',
          name: 'Analyze Test Coverage',
          config: {
            toolName: 'analyze_test_coverage',
            toolArgs: {}
          }
        },
        {
          id: 'analyze-code',
          type: 'tool',
          name: 'Analyze Code Quality',
          config: {
            toolName: 'analyze_code_quality',
            toolArgs: {
              includeHistory: true
            }
          }
        },
        {
          id: 'quality-gate',
          type: 'conditional',
          name: 'Quality Gate Check',
          config: {
            conditions: [
              {
                condition: 'coverage >= ${minCoverage} && qualityScore >= ${minQualityScore}',
                activities: [
                  {
                    id: 'approve',
                    type: 'tool',
                    name: 'Approve PR',
                    config: {
                      toolName: 'update_pr_status',
                      toolArgs: {
                        status: 'approved',
                        message: 'All quality checks passed!'
                      }
                    }
                  }
                ]
              }
            ],
            defaultBranch: [
              {
                id: 'request-review',
                type: 'human',
                name: 'Manual Review Required',
                config: {
                  prompt: 'Code quality checks failed. Coverage: ${coverage}%, Quality: ${qualityScore}. Please review manually.',
                  assignTo: ['tech-lead@company.com'],
                  approvalType: 'any'
                }
              }
            ]
          }
        }
      ],
      variables: {
        minCoverage: 80,
        minQualityScore: 75
      }
    }
  },
  
  {
    id: 'deployment-pipeline',
    name: 'Multi-Stage Deployment',
    description: 'Deploy through staging to production with approvals',
    category: 'operations',
    variables: {
      projectName: 'MyApp',
      stagingUrl: 'https://staging.myapp.com',
      productionUrl: 'https://myapp.com'
    },
    processDefinition: {
      name: '${projectName} Deployment Pipeline',
      description: 'Automated deployment with staging validation',
      version: '1.0.0',
      triggers: [
        {
          id: 'release-trigger',
          type: 'event',
          name: 'On Release Tag',
          enabled: true,
          config: {
            event: 'git_tag_created',
            filters: {
              pattern: 'v*'
            }
          }
        }
      ],
      activities: [
        {
          id: 'build',
          type: 'tool',
          name: 'Build Application',
          config: {
            toolName: 'execute_workflow',
            toolArgs: {
              workflowName: 'build-production'
            }
          }
        },
        {
          id: 'deploy-staging',
          type: 'tool',
          name: 'Deploy to Staging',
          config: {
            toolName: 'deploy_to_environment',
            toolArgs: {
              environment: 'staging',
              version: '${tagVersion}'
            }
          }
        },
        {
          id: 'run-e2e-tests',
          type: 'tool',
          name: 'Run E2E Tests on Staging',
          config: {
            toolName: 'run_tests',
            toolArgs: {
              suite: 'e2e',
              baseUrl: '${stagingUrl}'
            }
          }
        },
        {
          id: 'approval',
          type: 'human',
          name: 'Production Deployment Approval',
          config: {
            prompt: 'Staging deployment successful. E2E tests passed. Approve production deployment?',
            assignTo: ['devops@company.com', 'product@company.com'],
            approvalType: 'all',
            timeout: 3600000 // 1 hour
          }
        },
        {
          id: 'deploy-production',
          type: 'tool',
          name: 'Deploy to Production',
          config: {
            toolName: 'deploy_to_environment',
            toolArgs: {
              environment: 'production',
              version: '${tagVersion}'
            }
          },
          condition: 'approved === true'
        },
        {
          id: 'notify',
          type: 'parallel',
          name: 'Send Notifications',
          config: {
            branches: [
              [{
                id: 'notify-slack',
                type: 'external',
                name: 'Notify Slack',
                config: {
                  url: 'https://slack.com/api/chat.postMessage',
                  method: 'POST',
                  body: {
                    channel: '#deployments',
                    text: '🚀 ${projectName} ${tagVersion} deployed to production!'
                  }
                }
              }],
              [{
                id: 'notify-email',
                type: 'external',
                name: 'Send Email',
                config: {
                  url: 'https://api.sendgrid.com/v3/mail/send',
                  method: 'POST',
                  body: {
                    to: ['team@company.com'],
                    subject: 'Production Deployment: ${projectName} ${tagVersion}',
                    content: 'Successfully deployed to production.'
                  }
                }
              }]
            ],
            waitForAll: false
          }
        }
      ],
      variables: {
        projectName: 'MyApp',
        stagingUrl: 'https://staging.myapp.com',
        productionUrl: 'https://myapp.com'
      }
    }
  },
  
  {
    id: 'customer-onboarding',
    name: 'Customer Onboarding Flow',
    description: 'Automated new customer setup and onboarding',
    persona: 'ceo',
    category: 'customer',
    variables: {
      companyName: 'Your Company',
      onboardingDuration: 14
    },
    processDefinition: {
      name: 'Customer Onboarding - ${companyName}',
      description: 'Complete customer onboarding workflow',
      version: '1.0.0',
      triggers: [
        {
          id: 'signup-trigger',
          type: 'event',
          name: 'On Customer Signup',
          enabled: true,
          config: {
            event: 'customer_signup'
          }
        }
      ],
      activities: [
        {
          id: 'create-account',
          type: 'tool',
          name: 'Create Customer Account',
          config: {
            toolName: 'create_customer',
            toolArgs: {
              customerData: '${eventData.customer}'
            }
          }
        },
        {
          id: 'send-welcome',
          type: 'external',
          name: 'Send Welcome Email',
          config: {
            url: 'https://api.sendgrid.com/v3/mail/send',
            method: 'POST',
            body: {
              to: '${customer.email}',
              templateId: 'welcome-email-template',
              dynamicTemplateData: {
                customerName: '${customer.name}',
                companyName: '${companyName}'
              }
            }
          }
        },
        {
          id: 'create-project',
          type: 'tool',
          name: 'Initialize Customer Project',
          config: {
            toolName: 'init_atlas',
            toolArgs: {
              projectName: '${customer.company} Project'
            }
          }
        },
        {
          id: 'schedule-call',
          type: 'human',
          name: 'Schedule Onboarding Call',
          config: {
            prompt: 'Schedule onboarding call with ${customer.name} from ${customer.company}',
            assignTo: ['sales@company.com'],
            formFields: [
              { name: 'callDate', type: 'date', label: 'Call Date', required: true },
              { name: 'callTime', type: 'date', label: 'Call Time', required: true },
              { name: 'notes', type: 'text', label: 'Pre-call Notes' }
            ]
          }
        },
        {
          id: 'setup-services',
          type: 'parallel',
          name: 'Setup Customer Services',
          config: {
            branches: [
              [{
                id: 'setup-analytics',
                type: 'tool',
                name: 'Configure Analytics',
                config: {
                  toolName: 'setup_analytics',
                  toolArgs: { customerId: '${customer.id}' }
                }
              }],
              [{
                id: 'create-docs',
                type: 'tool',
                name: 'Generate Documentation',
                config: {
                  toolName: 'generate_readme',
                  toolArgs: {
                    projectName: '${customer.company}',
                    template: 'customer'
                  }
                }
              }],
              [{
                id: 'setup-billing',
                type: 'external',
                name: 'Setup Billing',
                config: {
                  url: 'https://api.stripe.com/v1/customers',
                  method: 'POST',
                  body: {
                    email: '${customer.email}',
                    name: '${customer.company}'
                  }
                }
              }]
            ],
            waitForAll: true
          }
        },
        {
          id: 'send-onboarding-kit',
          type: 'external',
          name: 'Send Onboarding Materials',
          config: {
            url: 'https://api.sendgrid.com/v3/mail/send',
            method: 'POST',
            body: {
              to: '${customer.email}',
              templateId: 'onboarding-kit-template',
              attachments: [
                { filename: 'getting-started.pdf' },
                { filename: 'api-guide.pdf' }
              ]
            }
          }
        }
      ],
      variables: {
        companyName: 'Your Company',
        onboardingDuration: 14
      }
    }
  },
  
  {
    id: 'data-backup',
    name: 'Automated Data Backup',
    description: 'Regular backup of critical data with verification',
    category: 'operations',
    variables: {
      backupTime: '02:00',
      retentionDays: 30,
      backupLocation: 's3://backups'
    },
    processDefinition: {
      name: 'Automated Data Backup',
      description: 'Nightly backup with verification and cleanup',
      version: '1.0.0',
      triggers: [
        {
          id: 'nightly-trigger',
          type: 'schedule',
          name: 'Nightly at ${backupTime}',
          enabled: true,
          config: {
            cron: '0 2 * * *' // 2 AM daily
          }
        }
      ],
      activities: [
        {
          id: 'create-backup',
          type: 'tool',
          name: 'Create Database Backup',
          config: {
            toolName: 'create_backup',
            toolArgs: {
              databases: ['production', 'analytics'],
              format: 'compressed'
            }
          }
        },
        {
          id: 'upload-backup',
          type: 'external',
          name: 'Upload to S3',
          config: {
            url: 'https://s3.amazonaws.com/${backupLocation}',
            method: 'PUT',
            headers: {
              'x-amz-server-side-encryption': 'AES256'
            },
            body: '${activityResults.create-backup.file}'
          }
        },
        {
          id: 'verify-backup',
          type: 'tool',
          name: 'Verify Backup Integrity',
          config: {
            toolName: 'verify_backup',
            toolArgs: {
              backupFile: '${activityResults.create-backup.file}',
              checksum: '${activityResults.create-backup.checksum}'
            }
          }
        },
        {
          id: 'cleanup-old',
          type: 'tool',
          name: 'Remove Old Backups',
          config: {
            toolName: 'cleanup_backups',
            toolArgs: {
              retentionDays: '${retentionDays}',
              location: '${backupLocation}'
            }
          }
        },
        {
          id: 'notify-status',
          type: 'conditional',
          name: 'Notify Backup Status',
          config: {
            conditions: [
              {
                condition: 'backupSuccess === true',
                activities: [{
                  id: 'notify-success',
                  type: 'tool',
                  name: 'Log Success',
                  config: {
                    toolName: 'store_memory',
                    toolArgs: {
                      category: 'backup',
                      content: 'Backup successful: ${backupSize} MB'
                    }
                  }
                }]
              }
            ],
            defaultBranch: [{
              id: 'notify-failure',
              type: 'external',
              name: 'Alert on Failure',
              config: {
                url: 'https://api.pagerduty.com/incidents',
                method: 'POST',
                body: {
                  incident: {
                    type: 'incident',
                    title: 'Backup Failed',
                    service: { id: 'backup-service' },
                    urgency: 'high'
                  }
                }
              }
            }]
          }
        }
      ],
      variables: {
        backupTime: '02:00',
        retentionDays: 30,
        backupLocation: 's3://backups'
      }
    }
  }
];

export function getProcessTemplate(templateId: string): ProcessTemplate | undefined {
  return processTemplates.find(t => t.id === templateId);
}

export function getTemplatesByPersona(persona: PersonaType): ProcessTemplate[] {
  return processTemplates.filter(t => t.persona === persona);
}

export function getTemplatesByCategory(category: ProcessTemplate['category']): ProcessTemplate[] {
  return processTemplates.filter(t => t.category === category);
}