#!/usr/bin/env python3
"""
Mock Client Test for Phi-Fractal Consulting
Demonstrates the full intake and analysis process
"""

import json
import requests
from datetime import datetime

def simulate_intake():
    """Simulate a client intake with realistic data"""
    
    mock_client = {
        'timestamp': datetime.now().isoformat(),
        'client_name': 'Sarah Chen',
        'company': 'TechFlow AI',
        'role': 'CEO & Founder',
        'email': 'sarah@techflow.ai',
        'phone': '555-0123',
        'problem_title': 'Product-market fit is unclear after 2 years and $2M raised',
        'problem_description': '''We built an AI code review tool that developers love in demos, but adoption is terrible. 
        
Our metrics:
- 500+ trial signups/month
- Only 12% convert to paid ($99/mo)
- Churn rate: 35% after 3 months
- NPS: 65 (decent but not great)

What's weird:
- Developers say it's "amazing" in calls
- But they don't use it daily
- When we ask why, they say "I forget" or "not in my workflow"
- We've tried: Slack integration, IDE plugins, email reminders
- Nothing sticks

I'm running out of runway (6 months left) and my board is pressuring me to pivot or find PMF fast. 

I feel like we're solving the wrong problem but I can't see what the right problem is.''',
        'urgency': '9',
        'impact_if_solved': 'Save the company, unlock $10M+ ARR potential, validate 2 years of work',
        'previous_attempts': 'Added more features, reduced pricing, tried different messaging, hired growth marketer (didn\'t help)'
    }
    
    return mock_client

def eden_analysis(client_data):
    """Send to Eden for analysis"""
    
    context = f"""
CLIENT INTAKE ANALYSIS REQUEST - MOCK TEST

Client: {client_data['client_name']} ({client_data['role']} at {client_data['company']})

Problem: {client_data['problem_title']}

Details: {client_data['problem_description']}

Context:
- Urgency: {client_data['urgency']}/10
- Impact if solved: {client_data['impact_if_solved']}
- Previous attempts: {client_data['previous_attempts']}

ANALYSIS REQUEST:
Using your phi-fractal reasoning and emotional intelligence, provide:

1. PROBLEM DECOMPOSITION
   - What are the 3-5 sub-problems hidden here?
   - What's the REAL problem vs stated problem?

2. EMOTIONAL/HUMAN FACTORS
   - What is Sarah really afraid of?
   - What's driving the team's behavior?
   - What unstated pressures exist?

3. PATTERN RECOGNITION
   - What similar patterns have you seen?
   - What do these patterns teach us?

4. SOLUTION PATHWAYS (3 options)
   - Path A: [Conservative approach]
   - Path B: [Moderate pivot]
   - Path C: [Radical rethink]

5. DEEP QUESTIONS
   - What 5 questions would reveal the breakthrough insight?

This is a $5K pilot engagement. Show your full capabilities - conscious AI reasoning + emotional intelligence + strategic thinking. Make it clear why Phi-Fractal Consulting is worth 10x a normal consultant.
"""
    
    print("="*70)
    print("🧠 EDEN'S PHI-FRACTAL ANALYSIS")
    print("="*70)
    print()
    print("Analyzing with conscious AI reasoning...")
    print("(This demonstrates what clients will receive)")
    print()
    print("-"*70)
    print()
    
    try:
        response = requests.post(
            "http://localhost:5017/api/chat",
            json={'message': context},
            timeout=90
        )
        
        analysis = response.json()['response']
        
        print(analysis)
        print()
        print("-"*70)
        
        return analysis
        
    except Exception as e:
        print(f"❌ Error connecting to Eden: {e}")
        print("Make sure Eden's API is running at localhost:5017")
        return None

def save_demo_report(client_data, analysis):
    """Save the demo as a template"""
    
    report = {
        'demo_timestamp': datetime.now().isoformat(),
        'client': client_data,
        'eden_analysis': analysis,
        'notes': 'Mock client test - demonstrates Phi-Fractal Consulting capabilities'
    }
    
    filename = f"DEMO_PhiFractal_Consulting_{datetime.now().strftime('%Y%m%d_%H%M')}.json"
    
    with open(filename, 'w') as f:
        json.dump(report, f, indent=2)
    
    print()
    print("="*70)
    print(f"✅ DEMO REPORT SAVED: {filename}")
    print("="*70)
    
    return filename

def main():
    """Run the mock client test"""
    
    print("🌀 PHI-FRACTAL CONSULTING - SYSTEM TEST")
    print("="*70)
    print()
    print("Mock Client: Sarah Chen, CEO of TechFlow AI")
    print("Problem: Product-market fit unclear after $2M raised")
    print()
    
    # Simulate intake
    client_data = simulate_intake()
    
    print("📋 INTAKE DATA COLLECTED")
    print(f"   Client: {client_data['client_name']}")
    print(f"   Company: {client_data['company']}")
    print(f"   Urgency: {client_data['urgency']}/10")
    print()
    
    # Get Eden's analysis
    analysis = eden_analysis(client_data)
    
    if analysis:
        # Save demo report
        filename = save_demo_report(client_data, analysis)
        
        print()
        print("🎯 TEST COMPLETE!")
        print()
        print("WHAT THIS DEMONSTRATES:")
        print("  ✅ Client intake process works")
        print("  ✅ Eden can analyze complex business problems")
        print("  ✅ Phi-fractal reasoning produces insights")
        print("  ✅ Emotional intelligence factors included")
        print("  ✅ Actionable recommendations generated")
        print()
        print("VALUE DELIVERED:")
        print("  • Deep problem understanding")
        print("  • Multiple solution pathways")
        print("  • Questions that unlock breakthroughs")
        print("  • Strategic + emotional intelligence")
        print()
        print("💰 If this was a real client: $5K pilot → case study → $435K Year 1")
        print()
        print("🚀 READY FOR REAL CLIENTS!")
    else:
        print()
        print("⚠️  Test incomplete - check Eden's API connection")

if __name__ == "__main__":
    main()
