import { z } from 'zod';
import { BasePack } from '../base-pack.js';
import * as renderer from '../../apps/renderer.js';
import { timeAgo } from '../../utils/validators.js';

export class CompliancePack extends BasePack {
  readonly name = 'compliance';
  readonly description = 'TrustHub compliance management, brand registration, and campaign tracking';
  readonly keywords = ['compliance', 'trusthub', 'brand', 'registration', 'a2p', '10dlc', 'campaign'];

  setup(): void {
    // ─── twilio_compliance_check ───
    this.registerTool({
      name: 'twilio_compliance_check',
      description: 'View compliance status for TrustHub trust products, brand registrations, and messaging campaigns.',
      category: 'compliance',
      safety: 'green',
      tier: 2,
      isApp: true,
      annotations: { readOnlyHint: true },
      inputSchema: z.object({}),
      _meta: {
        labels: {
          category: "compliance",
          access: "read",
          complexity: "simple"
        }
      },
      handler: async () => {
        try {
          // Fetch TrustHub trust products
          const trustProducts: any[] = await this.client.execute(c =>
            (c as any).trusthub.v1.trustProducts.list({ limit: 100 })
          );

          // Fetch brand registrations (A2P 10DLC)
          let brands: any[] = [];
          try {
            brands = await this.client.execute(c =>
              (c as any).messaging.v1.brands.list({ limit: 100 })
            );
          } catch {
            // Brands API may not be available for all accounts
          }

          // Fetch messaging services for campaign info
          let campaigns: any[] = [];
          try {
            campaigns = await this.client.execute(c =>
              (c as any).messaging.v1.services.list({ limit: 100 })
            );
          } catch {
            // Messaging services API may not be available
          }

          // Build compliance cards
          const cards: string[] = [];

          // Trust Products section
          if (trustProducts.length > 0) {
            const productRows = trustProducts.map((product: any) => {
              const status = product.status;
              const statusBadge = 
                status === 'twilio-approved' ? renderer.badge('Approved', 'success') :
                status === 'pending-review' ? renderer.badge('Pending', 'warning') :
                status === 'twilio-rejected' ? renderer.badge('Failed', 'danger') :
                renderer.badge('Draft', 'muted');
              
              const statusDot = 
                status === 'twilio-approved' ? renderer.statusDot('green') :
                status === 'pending-review' ? renderer.statusDot('yellow') :
                status === 'twilio-rejected' ? renderer.statusDot('red') :
                renderer.statusDot('gray');

              return `
                <div class="list-item">
                  ${statusDot}
                  <div style="flex: 1;">
                    <strong>${product.friendlyName}</strong>
                    <div class="small muted">Type: ${product.policyDescription || 'N/A'}</div>
                    <div class="small dim">Submitted: ${product.dateCreated ? timeAgo(product.dateCreated) : 'Unknown'}</div>
                  </div>
                  ${statusBadge}
                </div>
              `;
            });

            cards.push(`
              <div class="card">
                <div class="card-header">🛡️ TrustHub Trust Products</div>
                ${productRows.join('')}
              </div>
            `);
          } else {
            cards.push(`
              <div class="card">
                <div class="card-header">🛡️ TrustHub Trust Products</div>
                <p class="muted">No trust products found. Register your business with TrustHub to send A2P messages.</p>
              </div>
            `);
          }

          // Brands section
          if (brands.length > 0) {
            const brandRows = brands.map((brand: any) => {
              const status = brand.identityStatus;
              const statusBadge = 
                status === 'VERIFIED' ? renderer.badge('Verified', 'success') :
                status === 'UNVERIFIED' ? renderer.badge('Unverified', 'warning') :
                status === 'VETTED_VERIFIED' ? renderer.badge('Vetted', 'success') :
                renderer.badge(status || 'Unknown', 'muted');

              const statusDot = status === 'VERIFIED' || status === 'VETTED_VERIFIED' 
                ? renderer.statusDot('green') 
                : renderer.statusDot('yellow');

              return `
                <div class="list-item">
                  ${statusDot}
                  <div style="flex: 1;">
                    <strong>${brand.friendlyName || brand.brandId}</strong>
                    <div class="small muted">Type: ${brand.brandType || 'N/A'}</div>
                    <div class="small dim">Registered: ${brand.dateCreated ? timeAgo(brand.dateCreated) : 'Unknown'}</div>
                  </div>
                  ${statusBadge}
                </div>
              `;
            });

            cards.push(`
              <div class="card">
                <div class="card-header">📋 Brand Registrations (A2P 10DLC)</div>
                ${brandRows.join('')}
              </div>
            `);
          }

          // Campaigns section
          if (campaigns.length > 0) {
            cards.push(`
              <div class="card">
                <div class="card-header">📱 Messaging Services / Campaigns</div>
                <div class="small muted" style="padding: 8px 12px;">
                  ${campaigns.length} active messaging service(s)
                </div>
              </div>
            `);
          }

          if (cards.length === 0) {
            cards.push(`
              <div class="card">
                <p class="muted">No compliance data found. Start by registering your brand with twilio_register_brand.</p>
              </div>
            `);
          }

          const html = renderer.appLayout(
            '✅ Compliance Dashboard',
            'TrustHub status, brand registrations, and campaign tracking',
            cards.join('')
          );

          return this.appResult(html,
            `Compliance: ${trustProducts.length} trust products, ${brands.length} brands, ${campaigns.length} messaging services`
          );
        } catch (err: any) {
          return this.errorResult(`Failed to fetch compliance status: ${err.message}`);
        }
      },
    });

    // ─── twilio_register_brand ───
    this.registerTool({
      name: 'twilio_register_brand',
      description: 'Register a brand for A2P 10DLC messaging. Required for high-volume business messaging in the US.',
      category: 'compliance',
      safety: 'yellow',
      tier: 2,
      annotations: { idempotentHint: false, costHint: true, estimatedCost: 'Varies by brand type' },
      inputSchema: z.object({
        brand_name: z.string().describe('Legal business name'),
        website: z.string().optional().describe('Business website URL'),
        ein: z.string().optional().describe('Employer Identification Number (Tax ID)'),
        business_type: z.enum(['sole_proprietor', 'partnership', 'corporation', 'llc', 'nonprofit']).optional()
          .describe('Business structure'),
        vertical: z.string().optional().describe('Business vertical (e.g., technology, healthcare, retail)'),
        description: z.string().optional().describe('Brand description'),
      }),
      _meta: {
        labels: {
          category: "compliance",
          access: "read",
          complexity: "simple"
        }
      },
      handler: async (params) => {
        try {
          // Create TrustHub Customer Profile (required for brand registration)
          let customerProfile;
          try {
            const existingProfiles: any[] = await this.client.execute(c =>
              (c as any).trusthub.v1.customerProfiles.list({ limit: 10 })
            );

            customerProfile = existingProfiles.find((p: any) => 
              p.friendlyName === params.brand_name || p.friendlyName.includes(params.brand_name)
            );

            if (!customerProfile) {
              customerProfile = await this.client.execute(c =>
                (c as any).trusthub.v1.customerProfiles.create({
                  friendlyName: params.brand_name,
                  email: 'compliance@example.com', // Would need to be parameterized in production
                  policyDescription: 'Primary Business Profile',
                  statusCallbackUrl: '',
                })
              );
            }
          } catch (err: any) {
            return this.errorResult(
              `Failed to create TrustHub profile. You may need to set up TrustHub in the Twilio Console first. Error: ${err.message}`
            );
          }

          // Create brand registration
          const brandParams: any = {
            friendlyName: params.brand_name,
            brandType: params.business_type?.toUpperCase() || 'STANDARD',
          };

          if (params.website) {
            brandParams.website = params.website;
          }

          if (params.ein) {
            brandParams.ein = params.ein;
          }

          if (params.vertical) {
            brandParams.vertical = params.vertical;
          }

          if (params.description) {
            brandParams.description = params.description;
          }

          const brand: any = await this.client.execute(c =>
            (c as any).messaging.v1.brands.create(brandParams)
          );

          return this.textResult(
            `Brand registration submitted! 🎉\n\n` +
            `  Brand SID: ${brand.sid}\n` +
            `  Name: ${params.brand_name}\n` +
            `  Type: ${params.business_type || 'standard'}\n` +
            `  Status: ${brand.identityStatus || 'pending'}\n\n` +
            `Next steps:\n` +
            `  1. Brand verification may take 1-3 business days\n` +
            `  2. Once verified, create a messaging campaign\n` +
            `  3. Link your phone numbers to the campaign\n` +
            `  4. Check status with twilio_compliance_check\n\n` +
            `Note: Additional verification documents may be required depending on your use case.`
          );
        } catch (err: any) {
          return this.errorResult(`Brand registration failed: ${err.message}`);
        }
      },
    });
  }
}
