"""
W-M01: Agency Partner Outreach Emails

Email sequences targeting web agencies for widget resale partnership.
Value Prop: "Add AI voice to every client site. 30% recurring commission."
"""

from dataclasses import dataclass, field
from typing import List, Optional
from datetime import datetime
import re


# ============================================================================
# DATA MODELS
# ============================================================================

@dataclass
class Email:
    """Represents a single email in a sequence."""
    sequence_id: str
    email_number: int
    subject: str
    body: str
    cta: str
    delay_days: int  # Days after previous email in sequence


@dataclass
class EmailSequence:
    """Complete email sequence for an agency type."""
    agency_type: str
    emails: List[Email]
    
    def get_email_by_number(self, number: int) -> Optional[Email]:
        return next((e for e in self.emails if e.email_number == number), None)


@dataclass
class RevenueProjection:
    """Revenue calculator results."""
    client_count: int
    monthly_price_per_client: float
    commission_rate: float
    monthly_commission: float
    annual_commission: float
    
    def format_earnings(self) -> str:
        return f"""
╔══════════════════════════════════════════════════════════════╗
║           REVENUE PROJECTION - {self.client_count} CLIENTS                 ║
╠══════════════════════════════════════════════════════════════╣
║  Monthly Price/Client:     ${self.monthly_price_per_client:>8.2f}                   ║
║  Your Commission Rate:     {self.commission_rate:>8.0f}%                      ║
╠══════════════════════════════════════════════════════════════╣
║  MONTHLY COMMISSION:       ${self.monthly_commission:>8.2f}                   ║
║  ANNUAL COMMISSION:        ${self.annual_commission:>8.2f}                  ║
╚══════════════════════════════════════════════════════════════╝
"""


# ============================================================================
# REVENUE CALCULATOR
# ============================================================================

class RevenueCalculator:
    """
    Calculates partner commissions based on client count.
    
    Pricing Model:
    - Base price: $49/month per client site
    - Partner commission: 30% recurring
    
    Example Usage:
        calc = RevenueCalculator()
        projection = calc.calculate(50)  # 50 client sites
    """
    
    BASE_PRICE = 49.00  # Monthly price per client site
    COMMISSION_RATE = 0.30  # 30% recurring commission
    
    def calculate(self, client_count: int) -> RevenueProjection:
        """
        Calculate revenue projection for given client count.
        
        Args:
            client_count: Number of client sites using the widget
            
        Returns:
            RevenueProjection with calculated earnings
            
        Raises:
            ValueError: If client_count is negative
        """
        if client_count < 0:
            raise ValueError("Client count cannot be negative")
        
        total_monthly_revenue = client_count * self.BASE_PRICE
        monthly_commission = total_monthly_revenue * self.COMMISSION_RATE
        annual_commission = monthly_commission * 12
        
        return RevenueProjection(
            client_count=client_count,
            monthly_price_per_client=self.BASE_PRICE,
            commission_rate=self.COMMISSION_RATE * 100,
            monthly_commission=monthly_commission,
            annual_commission=annual_commission
        )
    
    def generate_attachment_content(self) -> str:
        """Generate revenue calculator table for email attachment."""
        scenarios = [10, 50, 200]
        
        table = """
╔════════════════════════════════════════════════════════════════════════╗
║            AI VOICE WIDGET - PARTNER REVENUE CALCULATOR               ║
╠════════════════════════════════════════════════════════════════════════╣
║  Pricing: $49/month per client site | Your Commission: 30% recurring  ║
╠════════════════════════════════════════════════════════════════════════╣
║   Clients    │  Monthly Revenue  │  Monthly Commission │ Annual Comm. ║
╠══════════════╪═══════════════════╪═════════════════════╪══════════════╣
"""
        for count in scenarios:
            proj = self.calculate(count)
            table += f"║   {count:>3}       │     ${proj.monthly_commission:>7.2f}      │       ${proj.monthly_commission:>7.2f}      │  ${proj.annual_commission:>8.2f}  ║\n"
        
        table += """╚════════════════════════════════════════════════════════════════════════╝

Ready to start? Book your partner demo call: [DEMO_LINK]

Questions? Reply to this email or contact partners@example.com
"""
        return table


# ============================================================================
# EMAIL SEQUENCES
# ============================================================================

class EmailSequenceGenerator:
    """
    Generates email sequences for agency partner outreach.
    
    Sequences:
    - Digital Agencies: General web/creative agencies
    - WordPress Agencies: WP-focused development shops
    - Shopify Agencies: E-commerce specialized agencies
    """
    
    VALUE_PROPOSITION = "Add AI voice to every client site. 30% recurring commission."
    BASE_CTA = "Book your partner demo call: https://example.com/partners/demo"
    
    # Common spam trigger words to avoid (white box test requirement)
    SPAM_WORDS = [
        'free money', 'guaranteed income', 'make money fast', 'no risk',
        'act now', 'limited time', 'urgent', 'winner', 'prize', 'cash bonus'
    ]
    
    def __init__(self):
        self.sequences = self._build_sequences()
    
    def _create_email(
        self, 
        sequence: str, 
        number: int, 
        subject: str, 
        body: str, 
        cta: str,
        delay: int
    ) -> Email:
        return Email(
            sequence_id=f"{sequence}_email_{number}",
            email_number=number,
            subject=subject,
            body=body,
            cta=cta,
            delay_days=delay
        )
    
    def _build_sequences(self) -> List[EmailSequence]:
        """Build all three email sequences."""
        return [
            self._build_digital_agencies_sequence(),
            self._build_wordpress_agencies_sequence(),
            self._build_shopify_agencies_sequence()
        ]
    
    def _build_digital_agencies_sequence(self) -> EmailSequence:
        """Digital agencies - general web/creative agencies."""
        emails = [
            self._create_email(
                sequence="digital",
                number=1,
                subject="Add AI voice to your client sites - 30% commission",
                body=f"""Hi {{name}},

Want to add recurring revenue to your agency without adding overhead?

We make AI voice integration simple for agencies like yours.

THE OPPORTUNITY:
{self.VALUE_PROPOSITION}

Your clients get cutting-edge AI voice technology. You get {30}% recurring commission on every site you enable.

We've partnered with 50+ agencies who are already earning.

See attached revenue calculator to see what you could earn with 10, 50, or 200 client sites.

Questions? Let's chat.

Best,
{{sender_name}}

---
Partner Team
{{company_name}}
""",
                cta=self.BASE_CTA,
                delay=0
            ),
            self._create_email(
                sequence="digital",
                number=2,
                subject="Quick question about your client services",
                body=f"""Hi {{name}},

Following up on my last email about adding AI voice to your service offerings.

This is a low-lift opportunity for your agency:
- We handle all technical implementation
- You provide the intro to your clients
- You earn {30}% recurring commission

One of our partner agencies added this to their retainer packages and now generates $3,000/month in passive commission.

Want to see how it works? 

{self.BASE_CTA}

Cheers,
{{sender_name}}
""",
                cta=self.BASE_CTA,
                delay=3
            ),
            self._create_email(
                sequence="digital",
                number=3,
                subject="Case study: How one agency added $36K/year",
                body=f"""Hi {{name}},

I wanted to share a quick success story:

Agency: 5-person web team in Melbourne
Clients: 45 active website clients
Result: $1,575/month recurring commission ($18,900/year)

They literally just added AI voice to their client proposals. That's it.

We've attached our revenue calculator so you can see projections for your client base.

Curious about the numbers for your agency?

{self.BASE_CTA}

Best,
{{sender_name}}
""",
                cta=self.BASE_CTA,
                delay=4
            ),
            self._create_email(
                sequence="digital",
                number=4,
                subject="Last chance to lock in partner terms",
                body=f"""Hi {{name}},

Just a quick note that we're updating our partner program terms next month.

If you sign up before then, you'll lock in the current {30}% commission rate forever.

Our team can walk you through:
- How the integration works (it's simple)
- What materials we provide for your clients
- How to pitch this as an upsell

Book a quick 15-min demo:

{self.BASE_CTA}

No pressure - just thought you'd want to know.

{{sender_name}}
""",
                cta=self.BASE_CTA,
                delay=5
            ),
            self._create_email(
                sequence="digital",
                number=5,
                subject="Ready to get started?",
                body=f"""Hi {{name}},

This will be my last email about our partner program for now.

We've had great response from agencies in {{{{city}}}}, and I'd love to include you.

Quick recap:
✓ Add AI voice to client sites
✓ {30}% recurring commission
✓ We handle all the tech
✓ Simple integration

If now isn't the right time, no worries. Just reply and let me know.

If you're ready to see how it works:

{self.BASE_CTA}

Thanks for your time, {{name}}.

Best,
{{sender_name}}

---
Unsubscribe: {{unsubscribe_link}}
""",
                cta=self.BASE_CTA,
                delay=7
            )
        ]
        return EmailSequence(agency_type="Digital Agencies", emails=emails)
    
    def _build_wordpress_agencies_sequence(self) -> EmailSequence:
        """WordPress agencies - WP-focused development shops."""
        emails = [
            self._create_email(
                sequence="wordpress",
                number=1,
                subject="AI voice for your WordPress sites - 30% commission",
                body=f"""Hi {{name}},

As a WordPress agency, you're always looking for ways to add value for clients.

Here's a simple addition to your service stack:

{self.VALUE_PROPOSITION}

We provide a WordPress plugin that adds AI voice to any site in minutes. Your clients get a cutting-edge feature. You get recurring revenue.

We've made it incredibly easy:
- One-click WordPress plugin install
- Your clients manage settings through wp-admin
- You earn {30}% on every active installation

See attached for earnings at 10/50/200 client sites.

Ready to learn more?

{self.BASE_CTA}

Best,
{{sender_name}}

---
WordPress Partner Program
{{company_name}}
""",
                cta=self.BASE_CTA,
                delay=0
            ),
            self._create_email(
                sequence="wordpress",
                number=2,
                subject="WordPress plugin + recurring revenue",
                body=f"""Hi {{name}},

Following up on our WordPress partner opportunity.

A few reasons agencies love this:

1. PLUGIN-BASED: Our WordPress plugin installs in under 2 minutes
2. WHITE-LABEL: Your clients see YOUR brand, not ours
3. PASSIVE INCOME: Set it up once, earn forever
4. NO SUPPORT: We handle all technical support

One WP agency added this to their maintenance packages and now earns $2,400/month from 40 clients.

Questions? Let's chat:

{self.BASE_CTA}

Cheers,
{{sender_name}}
""",
                cta=self.BASE_CTA,
                delay=3
            ),
            self._create_email(
                sequence="wordpress",
                number=3,
                subject="How WP agencies are adding $500+/month",
                body=f"""Hi {{name}},

Wanted to share how our WordPress partners are positioning this:

SERVICE TIERS:
- Basic: AI voice setup = $199 one-time
- Premium: AI voice + ongoing management = $49/month

The monthly option is where the real money is.

At 30% commission, you keep the difference between our $49 and whatever you charge.

See the attached revenue calculator for scenarios.

Want to discuss pricing strategy?

{self.BASE_CTA}

{{sender_name}}
""",
                cta=self.BASE_CTA,
                delay=4
            ),
            self._create_email(
                sequence="wordpress",
                number=4,
                subject="Your WordPress competitor is already earning",
                body=f"""Hi {{name}},

Quick insight: We just signed 3 WordPress agencies in {{{{city}}}} this month.

They're all offering AI voice as a premium add-on to existing clients.

If you're not offering this, your clients might ask your competitors.

No pressure - just making sure you're aware.

Our team can show you:
- How quick the WordPress installation is
- What sales materials we provide
- How to pitch it to your existing clients

Book a demo:

{self.BASE_CTA}

{{sender_name}}
""",
                cta=self.BASE_CTA,
                delay=5
            ),
            self._create_email(
                sequence="wordpress",
                number=5,
                subject="Let's get your WP partnership started",
                body=f"""Hi {{name}},

Final email in this sequence (I promise!).

If you're interested in our WordPress partner program, here's what happens next:

1. Book a 15-min demo (see below)
2. We walk through the plugin and partnership terms
3. You get access to our partner portal
4. Start promoting to clients

That's it. No commitment required to learn more.

{self.BASE_CTA}

If now isn't the right time, just reply and I'll remove you from this sequence.

Thanks, {{name}}.

Best,
{{sender_name}}

---
Unsubscribe: {{unsubscribe_link}}
""",
                cta=self.BASE_CTA,
                delay=7
            )
        ]
        return EmailSequence(agency_type="WordPress Agencies", emails=emails)
    
    def _build_shopify_agencies_sequence(self) -> EmailSequence:
        """Shopify agencies - E-commerce specialized agencies."""
        emails = [
            self._create_email(
                sequence="shopify",
                number=1,
                subject="AI voice for Shopify stores - 30% commission",
                body=f"""Hi {{name}},

Your Shopify clients are always looking for ways to increase conversions.

AI voice is the next big thing in e-commerce:

{self.VALUE_PROPOSITION}

Our Shopify app adds voice search and voice navigation to any store. It's a premium feature your clients will love paying for.

THE DEAL:
- Easy Shopify app installation
- You refer clients, we handle everything
- You earn {30}% recurring commission forever

Check the attached revenue calculator to see your potential earnings.

Curious? Let's talk:

{self.BASE_CTA}

Best,
{{sender_name}}

---
Shopify Partner Program
{{company_name}}
""",
                cta=self.BASE_CTA,
                delay=0
            ),
            self._create_email(
                sequence="shopify",
                number=2,
                subject="Increase your Shopify client LTV",
                body=f"""Hi {{name}},

Here's why Shopify agencies love this:

VOICE COMMERCE IS GROWING:
- 30% of shoppers now use voice search
- Voice users have 20% higher average order values
- Early adopters win

YOUR OPPORTUNITY:
Add AI voice to your Shopify client offerings and earn recurring revenue from every store you refer.

We handle:
- App installation and configuration
- Technical support
- Updates and maintenance

You handle:
- Introducing it to your clients
- Collecting your commission

See attached for earnings scenarios.

Questions?

{self.BASE_CTA}

{{sender_name}}
""",
                cta=self.BASE_CTA,
                delay=3
            ),
            self._create_email(
                sequence="shopify",
                number=3,
                subject="Shopify store example: 30% more engagement",
                body=f"""Hi {{name}},

One of our Shopify partner agencies recently shared results:

Client: Fashion e-commerce store
Result: 32% increase in product search engagement after adding voice

The store charges $99/month for voice features. At 30% commission, the agency earns $29.70/month per client.

With 50 Shopify stores, that's $1,485/month in passive income.

Our revenue calculator (attached) shows 10/50/200 client scenarios.

Ready to discuss?

{self.BASE_CTA}

Best,
{{sender_name}}
""",
                cta=self.BASE_CTA,
                delay=4
            ),
            self._create_email(
                sequence="shopify",
                number=4,
                subject="Shopify partner program update",
                body=f"""Hi {{name}},

Quick update: We're seeing strong interest from Shopify agencies right now.

If you're considering joining our partner program, here are current terms:

- Commission rate: {30}% recurring
- Minimum payout: $50/month
- Payment: Monthly via PayPal or bank transfer
- Term: 12-month agreement, cancel anytime

We also provide:
- Branded sales materials
- Co-marketing opportunities
- Priority support

Book a demo to lock in these terms:

{self.BASE_CTA}

{{sender_name}}
""",
                cta=self.BASE_CTA,
                delay=5
            ),
            self._create_email(
                sequence="shopify",
                number=5,
                subject="Start earning with your Shopify clients",
                body=f"""Hi {{name}},

Last email in this sequence.

Our Shopify partner program is the easiest way to add recurring revenue to your agency.

No extra work. No additional staff. Just add voice features to your client proposals.

If you're interested, let's chat:

{self.BASE_CTA}

If not, no hard feelings - just reply "stop" and I'll remove you.

Thanks for your time, {{name}}.

Best,
{{sender_name}}

---
Unsubscribe: {{unsubscribe_link}}
""",
                cta=self.BASE_CTA,
                delay=7
            )
        ]
        return EmailSequence(agency_type="Shopify Agencies", emails=emails)
    
    def get_sequence(self, agency_type: str) -> Optional[EmailSequence]:
        """Get sequence by agency type."""
        agency_type_lower = agency_type.lower()
        for seq in self.sequences:
            if seq.agency_type.lower() == agency_type_lower:
                return seq
        return None
    
    def get_all_sequences(self) -> List[EmailSequence]:
        return self.sequences
    
    def get_total_email_count(self) -> int:
        return sum(len(seq.emails) for seq in self.sequences)


# ============================================================================
# COMPLIANCE VALIDATOR
# ============================================================================

class ComplianceValidator:
    """
    Validates emails for CAN-SPAM (US) and Spam Act 2003 (Australia).
    
    Requirements:
    - Physical address or PO Box
    - Unsubscribe mechanism
    - No deceptive subject lines
    - Sender identification
    - Opt-out processing within 10 days
    """
    
    # Spam trigger words (for white box testing)
    SPAM_TRIGGERS = [
        'free money', 'guaranteed income', 'make money fast', 'no risk',
        'act now', 'limited time', 'urgent', 'winner', 'prize', 
        'cash bonus', '100% free', 'no obligation', 'risk-free'
    ]
    
    def __init__(self):
        self.violations = []
    
    def validate_email(self, email: Email, required_fields: dict) -> dict:
        """
        Validate a single email for compliance.
        
        Returns dict with 'valid' bool and 'violations' list.
        """
        self.violations = []
        
        # Check subject line for spam triggers
        self._check_subject_line(email.subject)
        
        # Check body for spam triggers
        self._check_body_for_spam(email.body)
        
        # Check required fields
        self._check_physical_address(required_fields.get('physical_address'))
        self._check_unsubscribe(email.body, email.cta)
        self._check_sender_identification(email.body, required_fields.get('sender_name'))
        
        return {
            'email_id': email.sequence_id,
            'valid': len(self.violations) == 0,
            'violations': self.violations.copy()
        }
    
    def _check_subject_line(self, subject: str):
        subject_lower = subject.lower()
        for trigger in self.SPAM_TRIGGERS:
            if trigger in subject_lower:
                self.violations.append(f"Spam trigger in subject: '{trigger}'")
    
    def _check_body_for_spam(self, body: str):
        body_lower = body.lower()
        for trigger in self.SPAM_TRIGGERS:
            if trigger in body_lower:
                self.violations.append(f"Spam trigger in body: '{trigger}'")
    
    def _check_physical_address(self, address: Optional[str]):
        if not address:
            self.violations.append("Missing physical address (required for CAN-SPAM)")
    
    def _check_unsubscribe(self, body: str, cta: str):
        combined = (body + cta).lower()
        if 'unsubscribe' not in combined:
            self.violations.append("Missing unsubscribe mechanism")
    
    def _check_sender_identification(self, body: str, sender_name: Optional[str]):
        if not sender_name:
            self.violations.append("Missing sender identification")


# ============================================================================
# WHITE BOX TESTS
# ============================================================================

class WhiteBoxTester:
    """
    Internal tests verifying:
    - Commission percentages match partner agreement (30%)
    - No spam words present
    - Unsubscribe mechanism included
    """
    
    EXPECTED_COMMISSION_RATE = 30
    
    def __init__(self, generator: EmailSequenceGenerator, validator: ComplianceValidator):
        self.generator = generator
        self.validator = validator
    
    def verify_commission_rates(self) -> dict:
        """Verify all emails mention correct 30% commission rate."""
        results = []
        
        for sequence in self.generator.get_all_sequences():
            for email in sequence.emails:
                body_text = (email.body + email.subject).lower()
                
                # Check for 30% or thirty percent
                has_correct_rate = (
                    '30%' in email.body or 
                    '30 %' in email.body or
                    'thirty percent' in body_text
                )
                
                # Check for any other percentage (shouldn't exist)
                percentage_matches = re.findall(r'\b(\d+)%', email.body)
                incorrect_rates = [p for p in percentage_matches if int(p) != 30]
                
                results.append({
                    'email_id': email.sequence_id,
                    'has_correct_rate': has_correct_rate,
                    'incorrect_rates_found': incorrect_rates,
                    'pass': has_correct_rate and len(incorrect_rates) == 0
                })
        
        all_pass = all(r['pass'] for r in results)
        return {
            'test_name': 'Commission Rate Verification',
            'passed': all_pass,
            'details': results
        }
    
    def verify_no_spam_words(self) -> dict:
        """Verify no spam trigger words in any email."""
        results = []
        
        for sequence in self.generator.get_all_sequences():
            for email in sequence.emails:
                combined = (email.subject + ' ' + email.body).lower()
                found_spam_words = []
                
                for word in self.validator.SPAM_TRIGGERS:
                    if word in combined:
                        found_spam_words.append(word)
                
                results.append({
                    'email_id': email.sequence_id,
                    'spam_words_found': found_spam_words,
                    'pass': len(found_spam_words) == 0
                })
        
        all_pass = all(r['pass'] for r in results)
        return {
            'test_name': 'Spam Word Verification',
            'passed': all_pass,
            'details': results
        }
    
    def verify_unsubscribe_mechanism(self) -> dict:
        """Verify unsubscribe mechanism present in all applicable emails."""
        results = []
        
        for sequence in self.generator.get_all_sequences():
            for email in sequence.emails:
                combined = (email.body + email.cta).lower()
                has_unsubscribe = 'unsubscribe' in combined
                
                results.append({
                    'email_id': email.sequence_id,
                    'has_unsubscribe': has_unsubscribe,
                    'pass': has_unsubscribe
                })
        
        # Only emails 4 and 5 in each sequence typically need unsubscribe
        # (first 3 can be business emails, but we'll include in all for safety)
        all_pass = all(r['pass'] for r in results)
        return {
            'test_name': 'Unsubscribe Mechanism Verification',
            'passed': all_pass,
            'details': results
        }
    
    def run_all_tests(self) -> dict:
        """Run all white box tests."""
        return {
            'test_suite': 'White Box Tests',
            'timestamp': datetime.now().isoformat(),
            'tests': [
                self.verify_commission_rates(),
                self.verify_no_spam_words(),
                self.verify_unsubscribe_mechanism()
            ]
        }


# ============================================================================
# BLACK BOX TESTS
# ============================================================================

class BlackBoxTester:
    """
    External tests verifying:
    - All 15 emails written (3 sequences x 5 emails)
    - Revenue calculator accurate
    - CTAs actionable
    - Compliance requirements met
    """
    
    def __init__(self, generator: EmailSequenceGenerator, calculator: RevenueCalculator):
        self.generator = generator
        self.calculator = calculator
    
    def test_all_emails_written(self) -> dict:
        """Verify all 15 emails exist."""
        total = self.generator.get_total_email_count()
        sequences = self.generator.get_all_sequences()
        
        return {
            'test_name': 'All Emails Written',
            'expected': 15,
            'actual': total,
            'passed': total == 15,
            'sequences': [
                {
                    'type': seq.agency_type,
                    'email_count': len(seq.emails)
                }
                for seq in sequences
            ]
        }
    
    def test_revenue_calculator_accuracy(self) -> dict:
        """Verify revenue calculator produces accurate results."""
        test_cases = [
            (10, 49.00 * 10 * 0.30),    # 10 clients: $147/month
            (50, 49.00 * 50 * 0.30),    # 50 clients: $735/month
            (200, 49.00 * 200 * 0.30),  # 200 clients: $2,940/month
        ]
        
        results = []
        for client_count, expected_monthly in test_cases:
            projection = self.calculator.calculate(client_count)
            annual = expected_monthly * 12
            
            results.append({
                'client_count': client_count,
                'expected_monthly': expected_monthly,
                'actual_monthly': projection.monthly_commission,
                'monthly_match': abs(expected_monthly - projection.monthly_commission) < 0.01,
                'expected_annual': annual,
                'actual_annual': projection.annual_commission,
                'annual_match': abs(annual - projection.annual_commission) < 0.01
            })
        
        all_pass = all(
            r['monthly_match'] and r['annual_match'] 
            for r in results
        )
        
        return {
            'test_name': 'Revenue Calculator Accuracy',
            'passed': all_pass,
            'details': results
        }
    
    def test_ctas_actionable(self) -> dict:
        """Verify all CTAs are actionable (contain booking link)."""
        results = []
        
        for sequence in self.generator.get_all_sequences():
            for email in sequence.emails:
                has_cta = len(email.cta) > 0
                has_link = 'http' in email.cta.lower() or '[demo_link]' in email.cta.lower()
                
                results.append({
                    'email_id': email.sequence_id,
                    'has_cta': has_cta,
                    'has_link': has_link,
                    'pass': has_cta and has_link
                })
        
        all_pass = all(r['pass'] for r in results)
        return {
            'test_name': 'CTA Actionability',
            'passed': all_pass,
            'details': results
        }
    
    def test_compliance_requirements(self) -> dict:
        """Verify compliance requirements for CAN-SPAM and Spam Act."""
        required_fields = {
            'physical_address': '123 Business St, Melbourne VIC 3000, Australia',
            'sender_name': 'Partner Team',
            'company_name': 'AI Voice Solutions'
        }
        
        validator = ComplianceValidator()
        results = []
        
        for sequence in self.generator.get_all_sequences():
            for email in sequence.emails:
                validation = validator.validate_email(email, required_fields)
                results.append(validation)
        
        all_pass = all(r['valid'] for r in results)
        return {
            'test_name': 'Compliance Requirements (CAN-SPAM + Spam Act)',
            'passed': all_pass,
            'details': results
        }
    
    def run_all_tests(self) -> dict:
        """Run all black box tests."""
        return {
            'test_suite': 'Black Box Tests',
            'timestamp': datetime.now().isoformat(),
            'tests': [
                self.test_all_emails_written(),
                self.test_revenue_calculator_accuracy(),
                self.test_ctas_actionable(),
                self.test_compliance_requirements()
            ]
        }


# ============================================================================
# EXAMPLE USAGE / MAIN
# ============================================================================

def main():
    """Demonstrate the email sequence system with test results."""
    
    print("=" * 70)
    print("W-M01: Agency Partner Outreach Emails")
    print("=" * 70)
    
    # Initialize components
    calculator = RevenueCalculator()
    generator = EmailSequenceGenerator()
    validator = ComplianceValidator()
    
    # Show revenue calculator output
    print("\n" + "=" * 70)
    print("REVENUE CALCULATOR OUTPUT")
    print("=" * 70)
    print(calculator.generate_attachment_content())
    
    # Show email counts
    print("\n" + "=" * 70)
    print("EMAIL SEQUENCES")
    print("=" * 70)
    for sequence in generator.get_all_sequences():
        print(f"\n{sequence.agency_type}: {len(sequence.emails)} emails")
        for email in sequence.emails:
            print(f"  - Email {email.email_number}: {email.subject[:50]}...")
    
    # Run tests
    print("\n" + "=" * 70)
    print("BLACK BOX TESTS")
    print("=" * 70)
    bb_tester = BlackBoxTester(generator, calculator)
    bb_results = bb_tester.run_all_tests()
    
    for test in bb_results['tests']:
        status = "✓ PASS" if test['passed'] else "✗ FAIL"
        print(f"\n{status}: {test['test_name']}")
    
    print("\n" + "=" * 70)
    print("WHITE BOX TESTS")
    print("=" * 70)
    wb_tester = WhiteBoxTester(generator, validator)
    wb_results = wb_tester.run_all_tests()
    
    for test in wb_results['tests']:
        status = "✓ PASS" if test['passed'] else "✗ FAIL"
        print(f"\n{status}: {test['test_name']}")
    
    # Summary
    print("\n" + "=" * 70)
    print("TEST SUMMARY")
    print("=" * 70)
    
    bb_passed = all(t['passed'] for t in bb_results['tests'])
    wb_passed = all(t['passed'] for t in wb_results['tests'])
    
    print(f"Black Box Tests: {'ALL PASSED ✓' if bb_passed else 'FAILED ✗'}")
    print(f"White Box Tests: {'ALL PASSED ✓' if wb_passed else 'FAILED ✗'}")
    print(f"\nTotal Emails: {generator.get_total_email_count()}")
    print(f"Commission Rate: {calculator.COMMISSION_RATE * 100}%")


if __name__ == "__main__":
    main()