1 line
85 KiB
JSON
1 line
85 KiB
JSON
{"repo": "anirudhbhanot/demoflash3", "files": {"api_michelin_strategic_analysis.py": {"ab889d31a3dfb15b6d06aced0cc9df8df600a068": {"t": 1785746415.8679624, "n": 39276, "h": "5c73e5e656d76ef2", "c": "#!/usr/bin/env python3\n\"\"\"\nMichelin 3-Phase Strategic Analysis API\nImplements the Michelin case study framework with DeepSeek integration\n\"\"\"\n\nimport os\nimport sys\nimport logging\nimport json\nimport asyncio\nfrom typing import Dict, List, Optional, Any, Tuple\nfrom datetime import datetime\nfrom fastapi import APIRouter, HTTPException\nfrom pydantic import BaseModel, Field\nimport aiohttp\nimport re\n\n# Add framework intelligence to path\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\nframework_dir = os.path.join(current_dir, 'framework_intelligence')\nsys.path.insert(0, framework_dir)\n\n# Setup logging\nlogger = logging.getLogger(__name__)\n\n# Import framework components\ntry:\n from framework_database import FRAMEWORKS\n FRAMEWORK_ANALYSIS_AVAILABLE = True\nexcept ImportError as e:\n logger.warning(f\"Framework analysis not available: {e}\")\n FRAMEWORK_ANALYSIS_AVAILABLE = False\n\n# Create router\nmichelin_router = APIRouter(prefix=\"/api/michelin\", tags=[\"Michelin Strategic Analysis\"])\n\n# DeepSeek API configuration\nDEEPSEEK_API_KEY = os.getenv(\"DEEPSEEK_API_KEY\", \"sk-f68b7148243e4663a31386a5ea6093cf\")\nDEEPSEEK_API_URL = \"https://api.deepseek.com/v1/chat/completions\"\n\n# Pydantic models for request/response\nclass MichelinAnalysisRequest(BaseModel):\n \"\"\"Request for Michelin 3-phase analysis\"\"\"\n startup_data: Dict[str, Any]\n analysis_depth: str = Field(default=\"comprehensive\", description=\"comprehensive, standard, or quick\")\n\nclass BCGMatrixAnalysis(BaseModel):\n position: str # Star, Cash Cow, Question Mark, or Dog\n market_growth: float\n relative_market_share: float\n strategic_implications: List[str]\n action_items: List[str]\n\nclass PortersFiveForces(BaseModel):\n competitive_rivalry: Dict[str, Any]\n threat_of_new_entrants: Dict[str, Any]\n bargaining_power_of_suppliers: Dict[str, Any]\n bargaining_power_of_buyers: Dict[str, Any]\n threat_of_substitutes: Dict[str, Any]\n overall_industry_attractiveness: str\n key_strategic_imperatives: List[str]\n\nclass SWOTAnalysis(BaseModel):\n strengths: List[Dict[str, str]]\n weaknesses: List[Dict[str, str]]\n opportunities: List[Dict[str, str]]\n threats: List[Dict[str, str]]\n strategic_priorities: List[str]\n\nclass Phase1Analysis(BaseModel):\n executive_summary: str\n bcg_matrix: BCGMatrixAnalysis\n porters_five_forces: PortersFiveForces\n swot_analysis: SWOTAnalysis\n current_position_narrative: str\n\nclass AnsoffMatrixAnalysis(BaseModel):\n market_penetration: Dict[str, Any]\n market_development: Dict[str, Any]\n product_development: Dict[str, Any]\n diversification: Dict[str, Any]\n recommended_strategy: str\n implementation_priorities: List[str]\n\nclass BlueOceanAnalysis(BaseModel):\n eliminate_factors: List[str]\n reduce_factors: List[str]\n raise_factors: List[str]\n create_factors: List[str]\n value_innovation_opportunities: List[Dict[str, Any]]\n new_market_spaces: List[str]\n\nclass GrowthScenario(BaseModel):\n name: str\n description: str\n revenue_projection_3yr: float\n investment_required: float\n key_milestones: List[str]\n risks: List[str]\n probability_of_success: float\n\nclass Phase2Analysis(BaseModel):\n strategic_options_overview: str\n ansoff_matrix: AnsoffMatrixAnalysis\n blue_ocean_strategy: BlueOceanAnalysis\n growth_scenarios: List[GrowthScenario]\n recommended_direction: str\n\nclass BalancedScorecardPerspective(BaseModel):\n perspective: str\n objectives: List[str]\n measures: List[str]\n targets: List[str]\n initiatives: List[str]\n\nclass OKRSet(BaseModel):\n quarter: str\n objectives: List[Dict[str, Any]]\n\nclass ResourceRequirements(BaseModel):\n human_resources: List[Dict[str, Any]]\n financial_resources: Dict[str, float]\n technology_resources: List[str]\n partnership_resources: List[str]\n\nclass RiskMitigationItem(BaseModel):\n risk: str\n impact: str\n likelihood: str\n mitigation_strategy: str\n contingency_plan: str\n\nclass Phase3Analysis(BaseModel):\n implementation_roadmap_summary: str\n balanced_scorecard: List[BalancedScorecardPerspective]\n okr_framework: List[OKRSet]\n resource_requirements: ResourceRequirements\n risk_mitigation_plan: List[RiskMitigationItem]\n success_metrics: List[Dict[str, Any]]\n\nclass MichelinAnalysisResponse(BaseModel):\n \"\"\"Complete Michelin 3-phase strategic analysis\"\"\"\n company_name: str\n analysis_date: str\n executive_briefing: str\n phase1: Phase1Analysis\n phase2: Phase2Analysis\n phase3: Phase3Analysis\n key_recommendations: List[str]\n critical_success_factors: List[str]\n next_steps: List[Dict[str, Any]]\n\nasync def call_deepseek_api(prompt: str, system_prompt: str = None) -> str:\n \"\"\"Call DeepSeek API with McKinsey consultant persona\"\"\"\n \n if not system_prompt:\n system_prompt = \"\"\"You are a senior McKinsey partner specializing in strategic transformation.\n You have 30+ years of experience advising Fortune 500 companies and high-growth startups.\n Your analysis should be:\n 1. Data-driven and specific with numbers\n 2. Framework-based but practical\n 3. Action-oriented with clear next steps\n 4. Confident without hedging\n 5. Written in professional consulting language\n \n Always provide specific metrics, timelines, and financial projections where relevant.\n Format your response as valid JSON matching the expected structure.\"\"\"\n \n messages = [\n {\"role\": \"system\", \"content\": system_prompt},\n {\"role\": \"user\", \"content\": prompt}\n ]\n \n async with aiohttp.ClientSession() as session:\n headers = {\n \"Authorization\": f\"Bearer {DEEPSEEK_API_KEY}\",\n \"Content-Type\": \"application/json\"\n }\n \n data = {\n \"model\": \"deepseek-chat\",\n \"messages\": messages,\n \"temperature\": 0.7,\n \"max_tokens\": 4000\n }\n \n try:\n async with session.post(DEEPSEEK_API_URL, headers=headers, json=data) as response:\n if response.status == 200:\n result = await response.json()\n return result['choices'][0]['message']['content']\n else:\n logger.error(f\"DeepSeek API error: {response.status}\")\n return None\n except Exception as e:\n logger.error(f\"DeepSeek API call failed: {e}\")\n return None\n\ndef _extract_json_from_response(response_text: str) -> Dict[str, Any]:\n \"\"\"Extract and parse JSON from LLM response\"\"\"\n if not response_text:\n return {}\n \n # Try to find JSON in markdown code blocks\n json_match = re.search(r'```json\\s*(.*?)\\s*```', response_text, re.DOTALL)\n if json_match:\n json_str = json_match.group(1)\n else:\n # Try to find raw JSON\n json_str = response_text.strip()\n \n try:\n return json.loads(json_str)\n except json.JSONDecodeError as e:\n logger.error(f\"JSON decode error: {e}\")\n # Try to fix common issues\n json_str = _fix_malformed_json(json_str)\n try:\n return json.loads(json_str)\n except:\n logger.error(\"Failed to parse JSON after fixing attempt\")\n return {}\n\ndef _fix_malformed_json(json_str: str) -> str:\n \"\"\"Fix common JSON formatting issues\"\"\"\n # Fix unquoted property names\n json_str = re.sub(r'(\\w+):', r'\"\\1\":', json_str)\n # Fix single quotes\n json_str = json_str.replace(\"'\", '\"')\n # Fix trailing commas\n json_str = re.sub(r',\\s*}', '}', json_str)\n json_str = re.sub(r',\\s*]', ']', json_str)\n return json_str\n\nasync def analyze_phase1_current_state(startup_data: Dict[str, Any]) -> Phase1Analysis:\n \"\"\"Phase 1: Where Are We Now? - Current state analysis\"\"\"\n \n # Extract key metrics\n revenue = startup_data.get('annual_revenue_run_rate', 0)\n growth_rate = startup_data.get('revenue_growth_rate_percent', 0)\n market_size = startup_data.get('tam_size_usd', 10000000000)\n burn_rate = startup_data.get('monthly_burn_usd', 50000)\n customers = startup_data.get('customer_count', 0)\n stage = startup_data.get('funding_stage', 'seed')\n sector = startup_data.get('sector', 'technology')\n \n prompt = f\"\"\"\n Analyze this {sector} {stage} startup for Phase 1 (Where Are We Now?):\n - Revenue: ${revenue:,.0f}\n - Growth Rate: {growth_rate}%\n - Market Size: ${market_size:,.0f}\n - Monthly Burn: ${burn_rate:,.0f}\n - Customers: {customers}\n - Full data: {json.dumps(startup_data)}\n \n Provide a comprehensive analysis using:\n 1. BCG Matrix positioning (with specific market share and growth calculations)\n 2. Porter's Five Forces (rate each force as Low/Medium/High with justification)\n 3. SWOT Analysis (3-4 items per quadrant with specific evidence)\n \n Return valid JSON matching this structure:\n {{\n \"executive_summary\": \"2-3 paragraph summary of current position\",\n \"bcg_matrix\": {{\n \"position\": \"Star|Cash Cow|Question Mark|Dog\",\n \"market_growth\": <number>,\n \"relative_market_share\": <number>,\n \"strategic_implications\": [\"implication1\", \"implication2\"],\n \"action_items\": [\"action1\", \"action2\"]\n }},\n \"porters_five_forces\": {{\n \"competitive_rivalry\": {{\"intensity\": \"Low|Medium|High\", \"factors\": [\"factor1\", \"factor2\"], \"score\": <1-5>}},\n \"threat_of_new_entrants\": {{\"intensity\": \"Low|Medium|High\", \"factors\": [\"factor1\", \"factor2\"], \"score\": <1-5>}},\n \"bargaining_power_of_suppliers\": {{\"intensity\": \"Low|Medium|High\", \"factors\": [\"factor1\", \"factor2\"], \"score\": <1-5>}},\n \"bargaining_power_of_buyers\": {{\"intensity\": \"Low|Medium|High\", \"factors\": [\"factor1\", \"factor2\"], \"score\": <1-5>}},\n \"threat_of_substitutes\": {{\"intensity\": \"Low|Medium|High\", \"factors\": [\"factor1\", \"factor2\"], \"score\": <1-5>}},\n \"overall_industry_attractiveness\": \"Low|Medium|High\",\n \"key_strategic_imperatives\": [\"imperative1\", \"imperative2\"]\n }},\n \"swot_analysis\": {{\n \"strengths\": [{{\"item\": \"strength1\", \"evidence\": \"specific data\"}}, {{\"item\": \"strength2\", \"evidence\": \"specific data\"}}],\n \"weaknesses\": [{{\"item\": \"weakness1\", \"impact\": \"specific impact\"}}, {{\"item\": \"weakness2\", \"impact\": \"specific impact\"}}],\n \"opportunities\": [{{\"item\": \"opportunity1\", \"potential\": \"specific value\"}}, {{\"item\": \"opportunity2\", \"potential\": \"specific value\"}}],\n \"threats\": [{{\"item\": \"threat1\", \"mitigation\": \"specific action\"}}, {{\"item\": \"threat2\", \"mitigation\": \"specific action\"}}],\n \"strategic_priorities\": [\"priority1\", \"priority2\", \"priority3\"]\n }},\n \"current_position_narrative\": \"3-4 paragraph narrative synthesizing all analyses\"\n }}\n \"\"\"\n \n response = await call_deepseek_api(prompt)\n if not response:\n return generate_fallback_phase1_analysis(startup_data)\n \n try:\n data = _extract_json_from_response(response)\n return Phase1Analysis(**data)\n except Exception as e:\n logger.error(f\"Failed to parse Phase 1 analysis: {e}\")\n return generate_fallback_phase1_analysis(startup_data)\n\ndef generate_fallback_phase1_analysis(startup_data: Dict[str, Any]) -> Phase1Analysis:\n \"\"\"Generate fallback Phase 1 analysis if API fails\"\"\"\n \n revenue = startup_data.get('annual_revenue_run_rate', 0)\n growth_rate = startup_data.get('revenue_growth_rate_percent', 30)\n market_size = startup_data.get('tam_size_usd', 10000000000)\n market_share = (revenue / market_size * 100) if market_size > 0 else 0\n \n # Determine BCG position\n if growth_rate > 20 and market_share > 1:\n position = \"Star\"\n elif growth_rate <= 20 and market_share > 1:\n position = \"Cash Cow\"\n elif growth_rate > 20 and market_share <= 1:\n position = \"Question Mark\"\n else:\n position = \"Dog\"\n \n return Phase1Analysis(\n executive_summary=f\"The company is positioned as a {position} in the BCG matrix with {market_share:.2f}% market share and {growth_rate}% growth rate. The startup shows promising indicators but faces typical early-stage challenges.\",\n bcg_matrix=BCGMatrixAnalysis(\n position=position,\n market_growth=growth_rate,\n relative_market_share=market_share,\n strategic_implications=[\n f\"Current {position} position requires {'aggressive growth investment' if position == 'Question Mark' else 'maintaining market position'}\",\n f\"Market share of {market_share:.2f}% indicates {'early stage with growth potential' if market_share < 1 else 'established presence'}\"\n ],\n action_items=[\n \"Focus on customer acquisition to increase market share\",\n \"Optimize burn rate to extend runway\",\n \"Build competitive moats through product differentiation\"\n ]\n ),\n porters_five_forces=PortersFiveForces(\n competitive_rivalry={\"intensity\": \"Medium\", \"factors\": [\"Growing market attracts competitors\", \"Product differentiation emerging\"], \"score\": 3},\n threat_of_new_entrants={\"intensity\": \"High\", \"factors\": [\"Low barriers to entry\", \"VC funding available\"], \"score\": 4},\n bargaining_power_of_suppliers={\"intensity\": \"Low\", \"factors\": [\"Multiple supplier options\", \"Standard technologies\"], \"score\": 2},\n bargaining_power_of_buyers={\"intensity\": \"Medium\", \"factors\": [\"Increasing options\", \"Price sensitivity\"], \"score\": 3},\n threat_of_substitutes={\"intensity\": \"Medium\", \"factors\": [\"Alternative solutions exist\", \"Switching costs moderate\"], \"score\": 3},\n overall_industry_attractiveness=\"Medium\",\n key_strategic_imperatives=[\n \"Build defensible competitive advantages\",\n \"Increase switching costs for customers\",\n \"Develop unique value propositions\"\n ]\n ),\n swot_analysis=SWOTAnalysis(\n strengths=[\n {\"item\": \"Early market entry\", \"evidence\": f\"{startup_data.get('customer_count', 0)} customers acquired\"},\n {\"item\": \"Strong team\", \"evidence\": f\"{startup_data.get('team_size_full_time', 5)} full-time employees\"}\n ],\n weaknesses=[\n {\"item\": \"Limited runway\", \"impact\": f\"Only {startup_data.get('runway_months', 12)} months of runway\"},\n {\"item\": \"High burn rate\", \"impact\": f\"${startup_data.get('monthly_burn_usd', 50000):,}/month burn\"}\n ],\n opportunities=[\n {\"item\": \"Large market\", \"potential\": f\"${market_size/1e9:.1f}B TAM\"},\n {\"item\": \"High growth rate\", \"potential\": f\"{growth_rate}% annual growth\"}\n ],\n threats=[\n {\"item\": \"Competition\", \"mitigation\": \"Build unique differentiators\"},\n {\"item\": \"Funding risk\", \"mitigation\": \"Improve unit economics\"}\n ],\n strategic_priorities=[\n \"Achieve product-market fit\",\n \"Extend runway through efficiency\",\n \"Build competitive advantages\"\n ]\n ),\n current_position_narrative=\"The startup is in a critical growth phase with promising early traction but faces typical challenges of resource constraints and market competition. The key to success lies in rapidly achieving product-market fit while maintaining capital efficiency.\"\n )\n\nasync def analyze_phase2_strategic_direction(startup_data: Dict[str, Any], phase1_results: Phase1Analysis) -> Phase2Analysis:\n \"\"\"Phase 2: Where Should We Go? - Strategic direction\"\"\"\n \n revenue = startup_data.get('annual_revenue_run_rate', 0)\n sector = startup_data.get('sector', 'technology')\n stage = startup_data.get('funding_stage', 'seed')\n \n prompt = f\"\"\"\n Based on the Phase 1 analysis showing the company as a {phase1_results.bcg_matrix.position} with these strategic priorities:\n {json.dumps(phase1_results.swot_analysis.strategic_priorities)}\n \n Analyze Phase 2 (Where Should We Go?) for this {sector} {stage} startup:\n - Current Revenue: ${revenue:,.0f}\n - Market Position: {phase1_results.bcg_matrix.position}\n - Key Strengths: {[s['item'] for s in phase1_results.swot_analysis.strengths[:2]]}\n - Key Opportunities: {[o['item'] for o in phase1_results.swot_analysis.opportunities[:2]]}\n \n Provide strategic direction using:\n 1. Ansoff Matrix (evaluate all 4 quadrants with specific initiatives)\n 2. Blue Ocean Strategy (specific factors to eliminate/reduce/raise/create)\n 3. Three growth scenarios (Conservative, Moderate, Aggressive)\n \n Return valid JSON matching this structure:\n {{\n \"strategic_options_overview\": \"2-3 paragraph overview of strategic choices\",\n \"ansoff_matrix\": {{\n \"market_penetration\": {{\"strategy\": \"description\", \"initiatives\": [\"init1\", \"init2\"], \"investment\": <number>, \"timeline\": \"X months\"}},\n \"market_development\": {{\"strategy\": \"description\", \"initiatives\": [\"init1\", \"init2\"], \"investment\": <number>, \"timeline\": \"X months\"}},\n \"product_development\": {{\"strategy\": \"description\", \"initiatives\": [\"init1\", \"init2\"], \"investment\": <number>, \"timeline\": \"X months\"}},\n \"diversification\": {{\"strategy\": \"description\", \"initiatives\": [\"init1\", \"init2\"], \"investment\": <number>, \"timeline\": \"X months\"}},\n \"recommended_strategy\": \"Which quadrant to focus on and why\",\n \"implementation_priorities\": [\"priority1\", \"priority2\", \"priority3\"]\n }},\n \"blue_ocean_strategy\": {{\n \"eliminate_factors\": [\"factor1\", \"factor2\"],\n \"reduce_factors\": [\"factor1\", \"factor2\"],\n \"raise_factors\": [\"factor1\", \"factor2\"],\n \"create_factors\": [\"factor1\", \"factor2\"],\n \"value_innovation_opportunities\": [{{\"opportunity\": \"description\", \"impact\": \"high|medium|low\", \"feasibility\": \"high|medium|low\"}}],\n \"new_market_spaces\": [\"space1\", \"space2\"]\n }},\n \"growth_scenarios\": [\n {{\n \"name\": \"Conservative\",\n \"description\": \"Low risk approach\",\n \"revenue_projection_3yr\": <number>,\n \"investment_required\": <number>,\n \"key_milestones\": [\"milestone1\", \"milestone2\"],\n \"risks\": [\"risk1\", \"risk2\"],\n \"probability_of_success\": <0-100>\n }},\n {{\n \"name\": \"Moderate\",\n \"description\": \"Balanced approach\",\n \"revenue_projection_3yr\": <number>,\n \"investment_required\": <number>,\n \"key_milestones\": [\"milestone1\", \"milestone2\"],\n \"risks\": [\"risk1\", \"risk2\"],\n \"probability_of_success\": <0-100>\n }},\n {{\n \"name\": \"Aggressive\",\n \"description\": \"High growth approach\",\n \"revenue_projection_3yr\": <number>,\n \"investment_required\": <number>,\n \"key_milestones\": [\"milestone1\", \"milestone2\"],\n \"risks\": [\"risk1\", \"risk2\"],\n \"probability_of_success\": <0-100>\n }}\n ],\n \"recommended_direction\": \"Clear recommendation with rationale\"\n }}\n \"\"\"\n \n response = await call_deepseek_api(prompt)\n if not response:\n return generate_fallback_phase2_analysis(startup_data)\n \n try:\n data = _extract_json_from_response(response)\n return Phase2Analysis(**data)\n except Exception as e:\n logger.error(f\"Failed to parse Phase 2 analysis: {e}\")\n return generate_fallback_phase2_analysis(startup_data)\n\ndef generate_fallback_phase2_analysis(startup_data: Dict[str, Any]) -> Phase2Analysis:\n \"\"\"Generate fallback Phase 2 analysis if API fails\"\"\"\n \n revenue = startup_data.get('annual_revenue_run_rate', 1000000)\n \n return Phase2Analysis(\n strategic_options_overview=\"The company has multiple growth paths available. Market penetration offers the lowest risk approach while product development could unlock new revenue streams.\",\n ansoff_matrix=AnsoffMatrixAnalysis(\n market_penetration={\n \"strategy\": \"Deepen presence in current market\",\n \"initiatives\": [\"Increase sales force\", \"Customer success program\"],\n \"investment\": revenue * 0.5,\n \"timeline\": \"12 months\"\n },\n market_development={\n \"strategy\": \"Expand to adjacent markets\",\n \"initiatives\": [\"Geographic expansion\", \"New customer segments\"],\n \"investment\": revenue * 0.8,\n \"timeline\": \"18 months\"\n },\n product_development={\n \"strategy\": \"Enhance product offerings\",\n \"initiatives\": [\"New features\", \"Platform capabilities\"],\n \"investment\": revenue * 0.6,\n \"timeline\": \"12 months\"\n },\n diversification={\n \"strategy\": \"New products for new markets\",\n \"initiatives\": [\"Strategic acquisition\", \"New product line\"],\n \"investment\": revenue * 1.5,\n \"timeline\": \"24 months\"\n },\n recommended_strategy=\"Market Penetration\",\n implementation_priorities=[\n \"Optimize current market position\",\n \"Build sales infrastructure\",\n \"Enhance customer retention\"\n ]\n ),\n blue_ocean_strategy=BlueOceanAnalysis(\n eliminate_factors=[\"Complex pricing models\", \"Long implementation times\"],\n reduce_factors=[\"Customer acquisition cost\", \"Feature complexity\"],\n raise_factors=[\"User experience quality\", \"Customer support\"],\n create_factors=[\"Self-service capabilities\", \"Industry-specific solutions\"],\n value_innovation_opportunities=[\n {\"opportunity\": \"Vertical-specific solution\", \"impact\": \"high\", \"feasibility\": \"medium\"},\n {\"opportunity\": \"Freemium model\", \"impact\": \"medium\", \"feasibility\": \"high\"}\n ],\n new_market_spaces=[\"Underserved SMB segment\", \"Industry-specific verticals\"]\n ),\n growth_scenarios=[\n GrowthScenario(\n name=\"Conservative\",\n description=\"Focus on existing market with incremental improvements\",\n revenue_projection_3yr=revenue * 3,\n investment_required=revenue * 0.5,\n key_milestones=[\"10% market share\", \"EBITDA positive\"],\n risks=[\"Slow growth\", \"Competitor advances\"],\n probability_of_success=80\n ),\n GrowthScenario(\n name=\"Moderate\",\n description=\"Balanced growth through market and product expansion\",\n revenue_projection_3yr=revenue * 5,\n investment_required=revenue * 1,\n key_milestones=[\"New market entry\", \"Product suite launch\"],\n risks=[\"Execution complexity\", \"Resource constraints\"],\n probability_of_success=60\n ),\n GrowthScenario(\n name=\"Aggressive\",\n description=\"Rapid expansion through multiple initiatives\",\n revenue_projection_3yr=revenue * 10,\n investment_required=revenue * 2,\n key_milestones=[\"Market leadership\", \"International expansion\"],\n risks=[\"High burn rate\", \"Quality issues\"],\n probability_of_success=40\n )\n ],\n recommended_direction=\"Pursue moderate growth strategy balancing market penetration with selective product enhancements. This optimizes risk-return profile while building sustainable competitive advantages.\"\n )\n\nasync def analyze_phase3_implementation(startup_data: Dict[str, Any], phase2_results: Phase2Analysis) -> Phase3Analysis:\n \"\"\"Phase 3: How to Get There? - Implementation roadmap\"\"\"\n \n revenue = startup_data.get('annual_revenue_run_rate', 0)\n team_size = startup_data.get('team_size_full_time', 5)\n burn_rate = startup_data.get('monthly_burn_usd', 50000)\n \n prompt = f\"\"\"\n Based on Phase 2 recommendation of {phase2_results.recommended_direction}, create Phase 3 implementation plan:\n - Current Revenue: ${revenue:,.0f}\n - Team Size: {team_size}\n - Burn Rate: ${burn_rate:,.0f}/month\n - Chosen Strategy: {phase2_results.ansoff_matrix.recommended_strategy}\n \n Provide detailed implementation plan using:\n 1. Balanced Scorecard (4 perspectives with specific KPIs)\n 2. OKR Framework (quarterly objectives and key results)\n 3. Resource Requirements (people, money, technology, partnerships)\n 4. Risk Mitigation Plan (top 5 risks with mitigation strategies)\n 5. Success Metrics (leading and lagging indicators)\n \n Return valid JSON matching this structure:\n {{\n \"implementation_roadmap_summary\": \"2-3 paragraph executive summary of implementation plan\",\n \"balanced_scorecard\": [\n {{\n \"perspective\": \"Financial\",\n \"objectives\": [\"objective1\", \"objective2\"],\n \"measures\": [\"measure1\", \"measure2\"],\n \"targets\": [\"target1\", \"target2\"],\n \"initiatives\": [\"initiative1\", \"initiative2\"]\n }},\n {{\n \"perspective\": \"Customer\",\n \"objectives\": [\"objective1\", \"objective2\"],\n \"measures\": [\"measure1\", \"measure2\"],\n \"targets\": [\"target1\", \"target2\"],\n \"initiatives\": [\"initiative1\", \"initiative2\"]\n }},\n {{\n \"perspective\": \"Internal Process\",\n \"objectives\": [\"objective1\", \"objective2\"],\n \"measures\": [\"measure1\", \"measure2\"],\n \"targets\": [\"target1\", \"target2\"],\n \"initiatives\": [\"initiative1\", \"initiative2\"]\n }},\n {{\n \"perspective\": \"Learning & Growth\",\n \"objectives\": [\"objective1\", \"objective2\"],\n \"measures\": [\"measure1\", \"measure2\"],\n \"targets\": [\"target1\", \"target2\"],\n \"initiatives\": [\"initiative1\", \"initiative2\"]\n }}\n ],\n \"okr_framework\": [\n {{\n \"quarter\": \"Q1 2025\",\n \"objectives\": [\n {{\n \"objective\": \"Achieve product-market fit\",\n \"key_results\": [\n {{\"kr\": \"Reach 100 paying customers\", \"current\": 50, \"target\": 100}},\n {{\"kr\": \"Achieve 90% retention rate\", \"current\": 75, \"target\": 90}},\n {{\"kr\": \"Generate $500K ARR\", \"current\": 250000, \"target\": 500000}}\n ]\n }}\n ]\n }},\n {{\n \"quarter\": \"Q2 2025\",\n \"objectives\": [\n {{\n \"objective\": \"Scale go-to-market\",\n \"key_results\": [\n {{\"kr\": \"Hire 5 sales reps\", \"current\": 2, \"target\": 7}},\n {{\"kr\": \"Launch partner program\", \"current\": 0, \"target\": 10}},\n {{\"kr\": \"Reach $1M ARR\", \"current\": 500000, \"target\": 1000000}}\n ]\n }}\n ]\n }}\n ],\n \"resource_requirements\": {{\n \"human_resources\": [\n {{\"role\": \"VP Sales\", \"level\": \"Senior\", \"timeline\": \"Q1\", \"cost\": 250000}},\n {{\"role\": \"Engineers\", \"count\": 5, \"timeline\": \"Q1-Q2\", \"cost\": 750000}}\n ],\n \"financial_resources\": {{\n \"total_capital_needed\": 5000000,\n \"runway_extension\": 18,\n \"monthly_burn_target\": 150000,\n \"revenue_targets\": {{\"Q1\": 125000, \"Q2\": 250000, \"Q3\": 400000, \"Q4\": 600000}}\n }},\n \"technology_resources\": [\"CRM system\", \"Analytics platform\", \"CI/CD infrastructure\"],\n \"partnership_resources\": [\"Channel partners\", \"Technology integrators\", \"Industry associations\"]\n }},\n \"risk_mitigation_plan\": [\n {{\n \"risk\": \"Customer acquisition costs exceed projections\",\n \"impact\": \"High\",\n \"likelihood\": \"Medium\",\n \"mitigation_strategy\": \"Implement product-led growth features\",\n \"contingency_plan\": \"Reduce paid marketing, focus on organic channels\"\n }},\n {{\n \"risk\": \"Key talent retention\",\n \"impact\": \"High\",\n \"likelihood\": \"Low\",\n \"mitigation_strategy\": \"Competitive compensation packages with equity\",\n \"contingency_plan\": \"Executive search firm on retainer\"\n }}\n ],\n \"success_metrics\": [\n {{\"metric\": \"Monthly Recurring Revenue\", \"type\": \"lagging\", \"target\": \"$100K by Q2\", \"frequency\": \"monthly\"}},\n {{\"metric\": \"Customer Acquisition Cost\", \"type\": \"leading\", \"target\": \"<$1000\", \"frequency\": \"weekly\"}},\n {{\"metric\": \"Net Promoter Score\", \"type\": \"leading\", \"target\": \">50\", \"frequency\": \"quarterly\"}},\n {{\"metric\": \"Runway Months\", \"type\": \"lagging\", \"target\": \">18\", \"frequency\": \"monthly\"}}\n ]\n }}\n \"\"\"\n \n response = await call_deepseek_api(prompt)\n if not response:\n return generate_fallback_phase3_analysis(startup_data)\n \n try:\n data = _extract_json_from_response(response)\n return Phase3Analysis(**data)\n except Exception as e:\n logger.error(f\"Failed to parse Phase 3 analysis: {e}\")\n return generate_fallback_phase3_analysis(startup_data)\n\ndef generate_fallback_phase3_analysis(startup_data: Dict[str, Any]) -> Phase3Analysis:\n \"\"\"Generate fallback Phase 3 analysis if API fails\"\"\"\n \n return Phase3Analysis(\n implementation_roadmap_summary=\"The implementation focuses on achieving product-market fit in Q1, scaling go-to-market in Q2-Q3, and preparing for Series A in Q4. Key success factors include maintaining capital efficiency while accelerating growth.\",\n balanced_scorecard=[\n BalancedScorecardPerspective(\n perspective=\"Financial\",\n objectives=[\"Achieve profitability\", \"Optimize burn rate\"],\n measures=[\"Monthly burn\", \"Revenue growth\"],\n targets=[\"<$100K/month\", \">30% MoM\"],\n initiatives=[\"Cost optimization\", \"Pricing strategy\"]\n ),\n BalancedScorecardPerspective(\n perspective=\"Customer\",\n objectives=[\"Improve satisfaction\", \"Increase retention\"],\n measures=[\"NPS score\", \"Churn rate\"],\n targets=[\">50\", \"<5%\"],\n initiatives=[\"Customer success program\", \"Product improvements\"]\n ),\n BalancedScorecardPerspective(\n perspective=\"Internal Process\",\n objectives=[\"Streamline operations\", \"Improve efficiency\"],\n measures=[\"Cycle time\", \"Automation rate\"],\n targets=[\"<2 days\", \">80%\"],\n initiatives=[\"Process automation\", \"Tool implementation\"]\n ),\n BalancedScorecardPerspective(\n perspective=\"Learning & Growth\",\n objectives=[\"Build team capabilities\", \"Foster innovation\"],\n measures=[\"Training hours\", \"Innovation index\"],\n targets=[\">40 hrs/year\", \">8/10\"],\n initiatives=[\"Training program\", \"Innovation labs\"]\n )\n ],\n okr_framework=[\n OKRSet(\n quarter=\"Q1 2025\",\n objectives=[\n {\n \"objective\": \"Achieve product-market fit\",\n \"key_results\": [\n {\"kr\": \"100 paying customers\", \"current\": 50, \"target\": 100},\n {\"kr\": \"90% retention rate\", \"current\": 75, \"target\": 90}\n ]\n }\n ]\n ),\n OKRSet(\n quarter=\"Q2 2025\",\n objectives=[\n {\n \"objective\": \"Scale revenue\",\n \"key_results\": [\n {\"kr\": \"$1M ARR\", \"current\": 500000, \"target\": 1000000},\n {\"kr\": \"5 enterprise deals\", \"current\": 1, \"target\": 5}\n ]\n }\n ]\n )\n ],\n resource_requirements=ResourceRequirements(\n human_resources=[\n {\"role\": \"VP Sales\", \"level\": \"Senior\", \"timeline\": \"Q1\", \"cost\": 250000},\n {\"role\": \"Engineers\", \"count\": 5, \"timeline\": \"Q1-Q2\", \"cost\": 750000}\n ],\n financial_resources={\n \"total_capital_needed\": 5000000,\n \"runway_extension\": 18,\n \"monthly_burn_target\": 150000\n },\n technology_resources=[\"Salesforce CRM\", \"Mixpanel Analytics\", \"AWS Infrastructure\"],\n partnership_resources=[\"Channel partners\", \"System integrators\"]\n ),\n risk_mitigation_plan=[\n RiskMitigationItem(\n risk=\"Market competition intensifies\",\n impact=\"High\",\n likelihood=\"Medium\",\n mitigation_strategy=\"Accelerate product differentiation\",\n contingency_plan=\"Focus on niche market segment\"\n ),\n RiskMitigationItem(\n risk=\"Funding environment deteriorates\",\n impact=\"High\",\n likelihood=\"Low\",\n mitigation_strategy=\"Extend runway, improve unit economics\",\n contingency_plan=\"Bridge financing from existing investors\"\n )\n ],\n success_metrics=[\n {\"metric\": \"ARR\", \"type\": \"lagging\", \"target\": \"$2M by year-end\", \"frequency\": \"monthly\"},\n {\"metric\": \"CAC Payback\", \"type\": \"leading\", \"target\": \"<12 months\", \"frequency\": \"monthly\"},\n {\"metric\": \"Employee NPS\", \"type\": \"leading\", \"target\": \">70\", \"frequency\": \"quarterly\"}\n ]\n )\n\n@michelin_router.post(\"/strategic-analysis\", response_model=MichelinAnalysisResponse)\nasync def perform_michelin_analysis(request: MichelinAnalysisRequest):\n \"\"\"Perform complete Michelin 3-phase strategic analysis\"\"\"\n \n try:\n startup_data = request.startup_data\n company_name = startup_data.get('company_name', 'Startup')\n \n # Execute all three phases\n logger.info(\"Starting Phase 1 analysis...\")\n phase1 = await analyze_phase1_current_state(startup_data)\n \n logger.info(\"Starting Phase 2 analysis...\")\n phase2 = await analyze_phase2_strategic_direction(startup_data, phase1)\n \n logger.info(\"Starting Phase 3 analysis...\")\n phase3 = await analyze_phase3_implementation(startup_data, phase2)\n \n # Generate executive briefing\n executive_briefing = f\"\"\"\n {company_name} is positioned as a {phase1.bcg_matrix.position} in its market with significant growth potential. \n The recommended strategic direction is {phase2.recommended_direction}. \n Implementation will require ${phase3.resource_requirements.financial_resources.get('total_capital_needed', 5000000):,.0f} \n in capital and focus on {phase3.okr_framework[0].objectives[0]['objective']} as the immediate priority.\n \n The company faces {phase1.porters_five_forces.overall_industry_attractiveness} industry attractiveness \n but can leverage its {phase1.swot_analysis.strengths[0]['item']} to capture market opportunity.\n Success hinges on executing the {phase2.ansoff_matrix.recommended_strategy} strategy while \n maintaining capital efficiency and achieving key milestones.\n \"\"\"\n \n # Extract key recommendations\n key_recommendations = [\n f\"Focus on {phase2.ansoff_matrix.recommended_strategy} as primary growth strategy\",\n f\"Target {phase3.okr_framework[0].objectives[0]['key_results'][0]['kr']}\",\n f\"Implement {phase3.balanced_scorecard[0].initiatives[0]} to improve financial performance\",\n f\"Mitigate '{phase3.risk_mitigation_plan[0].risk}' through {phase3.risk_mitigation_plan[0].mitigation_strategy}\"\n ]\n \n # Define critical success factors\n critical_success_factors = [\n \"Achieve product-market fit within 6 months\",\n \"Maintain burn rate below target while scaling\",\n \"Build competitive moats through differentiation\",\n \"Secure Series A funding within 12 months\"\n ]\n \n # Create next steps\n next_steps = [\n {\n \"timeline\": \"30 days\",\n \"actions\": [\n \"Finalize strategic plan with board approval\",\n \"Begin recruitment for key positions\",\n \"Launch first strategic initiative\"\n ]\n },\n {\n \"timeline\": \"60 days\",\n \"actions\": [\n \"Complete team scaling for Q1\",\n \"Implement new processes and systems\",\n \"Achieve first OKR milestone\"\n ]\n },\n {\n \"timeline\": \"90 days\",\n \"actions\": [\n \"Review Q1 performance against targets\",\n \"Adjust strategy based on learnings\",\n \"Prepare for next funding round\"\n ]\n }\n ]\n \n return MichelinAnalysisResponse(\n company_name=company_name,\n analysis_date=datetime.now().isoformat(),\n executive_briefing=executive_briefing.strip(),\n phase1=phase1,\n phase2=phase2,\n phase3=phase3,\n key_recommendations=key_recommendations,\n critical_success_factors=critical_success_factors,\n next_steps=next_steps\n )\n \n except Exception as e:\n logger.error(f\"Michelin analysis failed: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@michelin_router.get(\"/status\")\nasync def check_michelin_status():\n \"\"\"Check if Michelin analysis service is available\"\"\"\n return {\n \"status\": \"operational\",\n \"framework_analysis_available\": FRAMEWORK_ANALYSIS_AVAILABLE,\n \"deepseek_configured\": bool(DEEPSEEK_API_KEY),\n \"version\": \"1.0.0\"\n }\n\n# Shutdown handler for cleanup\nasync def shutdown_michelin_engine():\n \"\"\"Cleanup resources on shutdown\"\"\"\n logger.info(\"Shutting down Michelin analysis engine\")\n # Add any cleanup code here if needed"}, "9a26feece1b4977fe4d9e9d0965674854d3505bc": {"t": 1785763775.045605, "n": 39276, "h": "5c73e5e656d76ef2", "c": "#!/usr/bin/env python3\n\"\"\"\nMichelin 3-Phase Strategic Analysis API\nImplements the Michelin case study framework with DeepSeek integration\n\"\"\"\n\nimport os\nimport sys\nimport logging\nimport json\nimport asyncio\nfrom typing import Dict, List, Optional, Any, Tuple\nfrom datetime import datetime\nfrom fastapi import APIRouter, HTTPException\nfrom pydantic import BaseModel, Field\nimport aiohttp\nimport re\n\n# Add framework intelligence to path\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\nframework_dir = os.path.join(current_dir, 'framework_intelligence')\nsys.path.insert(0, framework_dir)\n\n# Setup logging\nlogger = logging.getLogger(__name__)\n\n# Import framework components\ntry:\n from framework_database import FRAMEWORKS\n FRAMEWORK_ANALYSIS_AVAILABLE = True\nexcept ImportError as e:\n logger.warning(f\"Framework analysis not available: {e}\")\n FRAMEWORK_ANALYSIS_AVAILABLE = False\n\n# Create router\nmichelin_router = APIRouter(prefix=\"/api/michelin\", tags=[\"Michelin Strategic Analysis\"])\n\n# DeepSeek API configuration\nDEEPSEEK_API_KEY = os.getenv(\"DEEPSEEK_API_KEY\", \"sk-f68b7148243e4663a31386a5ea6093cf\")\nDEEPSEEK_API_URL = \"https://api.deepseek.com/v1/chat/completions\"\n\n# Pydantic models for request/response\nclass MichelinAnalysisRequest(BaseModel):\n \"\"\"Request for Michelin 3-phase analysis\"\"\"\n startup_data: Dict[str, Any]\n analysis_depth: str = Field(default=\"comprehensive\", description=\"comprehensive, standard, or quick\")\n\nclass BCGMatrixAnalysis(BaseModel):\n position: str # Star, Cash Cow, Question Mark, or Dog\n market_growth: float\n relative_market_share: float\n strategic_implications: List[str]\n action_items: List[str]\n\nclass PortersFiveForces(BaseModel):\n competitive_rivalry: Dict[str, Any]\n threat_of_new_entrants: Dict[str, Any]\n bargaining_power_of_suppliers: Dict[str, Any]\n bargaining_power_of_buyers: Dict[str, Any]\n threat_of_substitutes: Dict[str, Any]\n overall_industry_attractiveness: str\n key_strategic_imperatives: List[str]\n\nclass SWOTAnalysis(BaseModel):\n strengths: List[Dict[str, str]]\n weaknesses: List[Dict[str, str]]\n opportunities: List[Dict[str, str]]\n threats: List[Dict[str, str]]\n strategic_priorities: List[str]\n\nclass Phase1Analysis(BaseModel):\n executive_summary: str\n bcg_matrix: BCGMatrixAnalysis\n porters_five_forces: PortersFiveForces\n swot_analysis: SWOTAnalysis\n current_position_narrative: str\n\nclass AnsoffMatrixAnalysis(BaseModel):\n market_penetration: Dict[str, Any]\n market_development: Dict[str, Any]\n product_development: Dict[str, Any]\n diversification: Dict[str, Any]\n recommended_strategy: str\n implementation_priorities: List[str]\n\nclass BlueOceanAnalysis(BaseModel):\n eliminate_factors: List[str]\n reduce_factors: List[str]\n raise_factors: List[str]\n create_factors: List[str]\n value_innovation_opportunities: List[Dict[str, Any]]\n new_market_spaces: List[str]\n\nclass GrowthScenario(BaseModel):\n name: str\n description: str\n revenue_projection_3yr: float\n investment_required: float\n key_milestones: List[str]\n risks: List[str]\n probability_of_success: float\n\nclass Phase2Analysis(BaseModel):\n strategic_options_overview: str\n ansoff_matrix: AnsoffMatrixAnalysis\n blue_ocean_strategy: BlueOceanAnalysis\n growth_scenarios: List[GrowthScenario]\n recommended_direction: str\n\nclass BalancedScorecardPerspective(BaseModel):\n perspective: str\n objectives: List[str]\n measures: List[str]\n targets: List[str]\n initiatives: List[str]\n\nclass OKRSet(BaseModel):\n quarter: str\n objectives: List[Dict[str, Any]]\n\nclass ResourceRequirements(BaseModel):\n human_resources: List[Dict[str, Any]]\n financial_resources: Dict[str, float]\n technology_resources: List[str]\n partnership_resources: List[str]\n\nclass RiskMitigationItem(BaseModel):\n risk: str\n impact: str\n likelihood: str\n mitigation_strategy: str\n contingency_plan: str\n\nclass Phase3Analysis(BaseModel):\n implementation_roadmap_summary: str\n balanced_scorecard: List[BalancedScorecardPerspective]\n okr_framework: List[OKRSet]\n resource_requirements: ResourceRequirements\n risk_mitigation_plan: List[RiskMitigationItem]\n success_metrics: List[Dict[str, Any]]\n\nclass MichelinAnalysisResponse(BaseModel):\n \"\"\"Complete Michelin 3-phase strategic analysis\"\"\"\n company_name: str\n analysis_date: str\n executive_briefing: str\n phase1: Phase1Analysis\n phase2: Phase2Analysis\n phase3: Phase3Analysis\n key_recommendations: List[str]\n critical_success_factors: List[str]\n next_steps: List[Dict[str, Any]]\n\nasync def call_deepseek_api(prompt: str, system_prompt: str = None) -> str:\n \"\"\"Call DeepSeek API with McKinsey consultant persona\"\"\"\n \n if not system_prompt:\n system_prompt = \"\"\"You are a senior McKinsey partner specializing in strategic transformation.\n You have 30+ years of experience advising Fortune 500 companies and high-growth startups.\n Your analysis should be:\n 1. Data-driven and specific with numbers\n 2. Framework-based but practical\n 3. Action-oriented with clear next steps\n 4. Confident without hedging\n 5. Written in professional consulting language\n \n Always provide specific metrics, timelines, and financial projections where relevant.\n Format your response as valid JSON matching the expected structure.\"\"\"\n \n messages = [\n {\"role\": \"system\", \"content\": system_prompt},\n {\"role\": \"user\", \"content\": prompt}\n ]\n \n async with aiohttp.ClientSession() as session:\n headers = {\n \"Authorization\": f\"Bearer {DEEPSEEK_API_KEY}\",\n \"Content-Type\": \"application/json\"\n }\n \n data = {\n \"model\": \"deepseek-chat\",\n \"messages\": messages,\n \"temperature\": 0.7,\n \"max_tokens\": 4000\n }\n \n try:\n async with session.post(DEEPSEEK_API_URL, headers=headers, json=data) as response:\n if response.status == 200:\n result = await response.json()\n return result['choices'][0]['message']['content']\n else:\n logger.error(f\"DeepSeek API error: {response.status}\")\n return None\n except Exception as e:\n logger.error(f\"DeepSeek API call failed: {e}\")\n return None\n\ndef _extract_json_from_response(response_text: str) -> Dict[str, Any]:\n \"\"\"Extract and parse JSON from LLM response\"\"\"\n if not response_text:\n return {}\n \n # Try to find JSON in markdown code blocks\n json_match = re.search(r'```json\\s*(.*?)\\s*```', response_text, re.DOTALL)\n if json_match:\n json_str = json_match.group(1)\n else:\n # Try to find raw JSON\n json_str = response_text.strip()\n \n try:\n return json.loads(json_str)\n except json.JSONDecodeError as e:\n logger.error(f\"JSON decode error: {e}\")\n # Try to fix common issues\n json_str = _fix_malformed_json(json_str)\n try:\n return json.loads(json_str)\n except:\n logger.error(\"Failed to parse JSON after fixing attempt\")\n return {}\n\ndef _fix_malformed_json(json_str: str) -> str:\n \"\"\"Fix common JSON formatting issues\"\"\"\n # Fix unquoted property names\n json_str = re.sub(r'(\\w+):', r'\"\\1\":', json_str)\n # Fix single quotes\n json_str = json_str.replace(\"'\", '\"')\n # Fix trailing commas\n json_str = re.sub(r',\\s*}', '}', json_str)\n json_str = re.sub(r',\\s*]', ']', json_str)\n return json_str\n\nasync def analyze_phase1_current_state(startup_data: Dict[str, Any]) -> Phase1Analysis:\n \"\"\"Phase 1: Where Are We Now? - Current state analysis\"\"\"\n \n # Extract key metrics\n revenue = startup_data.get('annual_revenue_run_rate', 0)\n growth_rate = startup_data.get('revenue_growth_rate_percent', 0)\n market_size = startup_data.get('tam_size_usd', 10000000000)\n burn_rate = startup_data.get('monthly_burn_usd', 50000)\n customers = startup_data.get('customer_count', 0)\n stage = startup_data.get('funding_stage', 'seed')\n sector = startup_data.get('sector', 'technology')\n \n prompt = f\"\"\"\n Analyze this {sector} {stage} startup for Phase 1 (Where Are We Now?):\n - Revenue: ${revenue:,.0f}\n - Growth Rate: {growth_rate}%\n - Market Size: ${market_size:,.0f}\n - Monthly Burn: ${burn_rate:,.0f}\n - Customers: {customers}\n - Full data: {json.dumps(startup_data)}\n \n Provide a comprehensive analysis using:\n 1. BCG Matrix positioning (with specific market share and growth calculations)\n 2. Porter's Five Forces (rate each force as Low/Medium/High with justification)\n 3. SWOT Analysis (3-4 items per quadrant with specific evidence)\n \n Return valid JSON matching this structure:\n {{\n \"executive_summary\": \"2-3 paragraph summary of current position\",\n \"bcg_matrix\": {{\n \"position\": \"Star|Cash Cow|Question Mark|Dog\",\n \"market_growth\": <number>,\n \"relative_market_share\": <number>,\n \"strategic_implications\": [\"implication1\", \"implication2\"],\n \"action_items\": [\"action1\", \"action2\"]\n }},\n \"porters_five_forces\": {{\n \"competitive_rivalry\": {{\"intensity\": \"Low|Medium|High\", \"factors\": [\"factor1\", \"factor2\"], \"score\": <1-5>}},\n \"threat_of_new_entrants\": {{\"intensity\": \"Low|Medium|High\", \"factors\": [\"factor1\", \"factor2\"], \"score\": <1-5>}},\n \"bargaining_power_of_suppliers\": {{\"intensity\": \"Low|Medium|High\", \"factors\": [\"factor1\", \"factor2\"], \"score\": <1-5>}},\n \"bargaining_power_of_buyers\": {{\"intensity\": \"Low|Medium|High\", \"factors\": [\"factor1\", \"factor2\"], \"score\": <1-5>}},\n \"threat_of_substitutes\": {{\"intensity\": \"Low|Medium|High\", \"factors\": [\"factor1\", \"factor2\"], \"score\": <1-5>}},\n \"overall_industry_attractiveness\": \"Low|Medium|High\",\n \"key_strategic_imperatives\": [\"imperative1\", \"imperative2\"]\n }},\n \"swot_analysis\": {{\n \"strengths\": [{{\"item\": \"strength1\", \"evidence\": \"specific data\"}}, {{\"item\": \"strength2\", \"evidence\": \"specific data\"}}],\n \"weaknesses\": [{{\"item\": \"weakness1\", \"impact\": \"specific impact\"}}, {{\"item\": \"weakness2\", \"impact\": \"specific impact\"}}],\n \"opportunities\": [{{\"item\": \"opportunity1\", \"potential\": \"specific value\"}}, {{\"item\": \"opportunity2\", \"potential\": \"specific value\"}}],\n \"threats\": [{{\"item\": \"threat1\", \"mitigation\": \"specific action\"}}, {{\"item\": \"threat2\", \"mitigation\": \"specific action\"}}],\n \"strategic_priorities\": [\"priority1\", \"priority2\", \"priority3\"]\n }},\n \"current_position_narrative\": \"3-4 paragraph narrative synthesizing all analyses\"\n }}\n \"\"\"\n \n response = await call_deepseek_api(prompt)\n if not response:\n return generate_fallback_phase1_analysis(startup_data)\n \n try:\n data = _extract_json_from_response(response)\n return Phase1Analysis(**data)\n except Exception as e:\n logger.error(f\"Failed to parse Phase 1 analysis: {e}\")\n return generate_fallback_phase1_analysis(startup_data)\n\ndef generate_fallback_phase1_analysis(startup_data: Dict[str, Any]) -> Phase1Analysis:\n \"\"\"Generate fallback Phase 1 analysis if API fails\"\"\"\n \n revenue = startup_data.get('annual_revenue_run_rate', 0)\n growth_rate = startup_data.get('revenue_growth_rate_percent', 30)\n market_size = startup_data.get('tam_size_usd', 10000000000)\n market_share = (revenue / market_size * 100) if market_size > 0 else 0\n \n # Determine BCG position\n if growth_rate > 20 and market_share > 1:\n position = \"Star\"\n elif growth_rate <= 20 and market_share > 1:\n position = \"Cash Cow\"\n elif growth_rate > 20 and market_share <= 1:\n position = \"Question Mark\"\n else:\n position = \"Dog\"\n \n return Phase1Analysis(\n executive_summary=f\"The company is positioned as a {position} in the BCG matrix with {market_share:.2f}% market share and {growth_rate}% growth rate. The startup shows promising indicators but faces typical early-stage challenges.\",\n bcg_matrix=BCGMatrixAnalysis(\n position=position,\n market_growth=growth_rate,\n relative_market_share=market_share,\n strategic_implications=[\n f\"Current {position} position requires {'aggressive growth investment' if position == 'Question Mark' else 'maintaining market position'}\",\n f\"Market share of {market_share:.2f}% indicates {'early stage with growth potential' if market_share < 1 else 'established presence'}\"\n ],\n action_items=[\n \"Focus on customer acquisition to increase market share\",\n \"Optimize burn rate to extend runway\",\n \"Build competitive moats through product differentiation\"\n ]\n ),\n porters_five_forces=PortersFiveForces(\n competitive_rivalry={\"intensity\": \"Medium\", \"factors\": [\"Growing market attracts competitors\", \"Product differentiation emerging\"], \"score\": 3},\n threat_of_new_entrants={\"intensity\": \"High\", \"factors\": [\"Low barriers to entry\", \"VC funding available\"], \"score\": 4},\n bargaining_power_of_suppliers={\"intensity\": \"Low\", \"factors\": [\"Multiple supplier options\", \"Standard technologies\"], \"score\": 2},\n bargaining_power_of_buyers={\"intensity\": \"Medium\", \"factors\": [\"Increasing options\", \"Price sensitivity\"], \"score\": 3},\n threat_of_substitutes={\"intensity\": \"Medium\", \"factors\": [\"Alternative solutions exist\", \"Switching costs moderate\"], \"score\": 3},\n overall_industry_attractiveness=\"Medium\",\n key_strategic_imperatives=[\n \"Build defensible competitive advantages\",\n \"Increase switching costs for customers\",\n \"Develop unique value propositions\"\n ]\n ),\n swot_analysis=SWOTAnalysis(\n strengths=[\n {\"item\": \"Early market entry\", \"evidence\": f\"{startup_data.get('customer_count', 0)} customers acquired\"},\n {\"item\": \"Strong team\", \"evidence\": f\"{startup_data.get('team_size_full_time', 5)} full-time employees\"}\n ],\n weaknesses=[\n {\"item\": \"Limited runway\", \"impact\": f\"Only {startup_data.get('runway_months', 12)} months of runway\"},\n {\"item\": \"High burn rate\", \"impact\": f\"${startup_data.get('monthly_burn_usd', 50000):,}/month burn\"}\n ],\n opportunities=[\n {\"item\": \"Large market\", \"potential\": f\"${market_size/1e9:.1f}B TAM\"},\n {\"item\": \"High growth rate\", \"potential\": f\"{growth_rate}% annual growth\"}\n ],\n threats=[\n {\"item\": \"Competition\", \"mitigation\": \"Build unique differentiators\"},\n {\"item\": \"Funding risk\", \"mitigation\": \"Improve unit economics\"}\n ],\n strategic_priorities=[\n \"Achieve product-market fit\",\n \"Extend runway through efficiency\",\n \"Build competitive advantages\"\n ]\n ),\n current_position_narrative=\"The startup is in a critical growth phase with promising early traction but faces typical challenges of resource constraints and market competition. The key to success lies in rapidly achieving product-market fit while maintaining capital efficiency.\"\n )\n\nasync def analyze_phase2_strategic_direction(startup_data: Dict[str, Any], phase1_results: Phase1Analysis) -> Phase2Analysis:\n \"\"\"Phase 2: Where Should We Go? - Strategic direction\"\"\"\n \n revenue = startup_data.get('annual_revenue_run_rate', 0)\n sector = startup_data.get('sector', 'technology')\n stage = startup_data.get('funding_stage', 'seed')\n \n prompt = f\"\"\"\n Based on the Phase 1 analysis showing the company as a {phase1_results.bcg_matrix.position} with these strategic priorities:\n {json.dumps(phase1_results.swot_analysis.strategic_priorities)}\n \n Analyze Phase 2 (Where Should We Go?) for this {sector} {stage} startup:\n - Current Revenue: ${revenue:,.0f}\n - Market Position: {phase1_results.bcg_matrix.position}\n - Key Strengths: {[s['item'] for s in phase1_results.swot_analysis.strengths[:2]]}\n - Key Opportunities: {[o['item'] for o in phase1_results.swot_analysis.opportunities[:2]]}\n \n Provide strategic direction using:\n 1. Ansoff Matrix (evaluate all 4 quadrants with specific initiatives)\n 2. Blue Ocean Strategy (specific factors to eliminate/reduce/raise/create)\n 3. Three growth scenarios (Conservative, Moderate, Aggressive)\n \n Return valid JSON matching this structure:\n {{\n \"strategic_options_overview\": \"2-3 paragraph overview of strategic choices\",\n \"ansoff_matrix\": {{\n \"market_penetration\": {{\"strategy\": \"description\", \"initiatives\": [\"init1\", \"init2\"], \"investment\": <number>, \"timeline\": \"X months\"}},\n \"market_development\": {{\"strategy\": \"description\", \"initiatives\": [\"init1\", \"init2\"], \"investment\": <number>, \"timeline\": \"X months\"}},\n \"product_development\": {{\"strategy\": \"description\", \"initiatives\": [\"init1\", \"init2\"], \"investment\": <number>, \"timeline\": \"X months\"}},\n \"diversification\": {{\"strategy\": \"description\", \"initiatives\": [\"init1\", \"init2\"], \"investment\": <number>, \"timeline\": \"X months\"}},\n \"recommended_strategy\": \"Which quadrant to focus on and why\",\n \"implementation_priorities\": [\"priority1\", \"priority2\", \"priority3\"]\n }},\n \"blue_ocean_strategy\": {{\n \"eliminate_factors\": [\"factor1\", \"factor2\"],\n \"reduce_factors\": [\"factor1\", \"factor2\"],\n \"raise_factors\": [\"factor1\", \"factor2\"],\n \"create_factors\": [\"factor1\", \"factor2\"],\n \"value_innovation_opportunities\": [{{\"opportunity\": \"description\", \"impact\": \"high|medium|low\", \"feasibility\": \"high|medium|low\"}}],\n \"new_market_spaces\": [\"space1\", \"space2\"]\n }},\n \"growth_scenarios\": [\n {{\n \"name\": \"Conservative\",\n \"description\": \"Low risk approach\",\n \"revenue_projection_3yr\": <number>,\n \"investment_required\": <number>,\n \"key_milestones\": [\"milestone1\", \"milestone2\"],\n \"risks\": [\"risk1\", \"risk2\"],\n \"probability_of_success\": <0-100>\n }},\n {{\n \"name\": \"Moderate\",\n \"description\": \"Balanced approach\",\n \"revenue_projection_3yr\": <number>,\n \"investment_required\": <number>,\n \"key_milestones\": [\"milestone1\", \"milestone2\"],\n \"risks\": [\"risk1\", \"risk2\"],\n \"probability_of_success\": <0-100>\n }},\n {{\n \"name\": \"Aggressive\",\n \"description\": \"High growth approach\",\n \"revenue_projection_3yr\": <number>,\n \"investment_required\": <number>,\n \"key_milestones\": [\"milestone1\", \"milestone2\"],\n \"risks\": [\"risk1\", \"risk2\"],\n \"probability_of_success\": <0-100>\n }}\n ],\n \"recommended_direction\": \"Clear recommendation with rationale\"\n }}\n \"\"\"\n \n response = await call_deepseek_api(prompt)\n if not response:\n return generate_fallback_phase2_analysis(startup_data)\n \n try:\n data = _extract_json_from_response(response)\n return Phase2Analysis(**data)\n except Exception as e:\n logger.error(f\"Failed to parse Phase 2 analysis: {e}\")\n return generate_fallback_phase2_analysis(startup_data)\n\ndef generate_fallback_phase2_analysis(startup_data: Dict[str, Any]) -> Phase2Analysis:\n \"\"\"Generate fallback Phase 2 analysis if API fails\"\"\"\n \n revenue = startup_data.get('annual_revenue_run_rate', 1000000)\n \n return Phase2Analysis(\n strategic_options_overview=\"The company has multiple growth paths available. Market penetration offers the lowest risk approach while product development could unlock new revenue streams.\",\n ansoff_matrix=AnsoffMatrixAnalysis(\n market_penetration={\n \"strategy\": \"Deepen presence in current market\",\n \"initiatives\": [\"Increase sales force\", \"Customer success program\"],\n \"investment\": revenue * 0.5,\n \"timeline\": \"12 months\"\n },\n market_development={\n \"strategy\": \"Expand to adjacent markets\",\n \"initiatives\": [\"Geographic expansion\", \"New customer segments\"],\n \"investment\": revenue * 0.8,\n \"timeline\": \"18 months\"\n },\n product_development={\n \"strategy\": \"Enhance product offerings\",\n \"initiatives\": [\"New features\", \"Platform capabilities\"],\n \"investment\": revenue * 0.6,\n \"timeline\": \"12 months\"\n },\n diversification={\n \"strategy\": \"New products for new markets\",\n \"initiatives\": [\"Strategic acquisition\", \"New product line\"],\n \"investment\": revenue * 1.5,\n \"timeline\": \"24 months\"\n },\n recommended_strategy=\"Market Penetration\",\n implementation_priorities=[\n \"Optimize current market position\",\n \"Build sales infrastructure\",\n \"Enhance customer retention\"\n ]\n ),\n blue_ocean_strategy=BlueOceanAnalysis(\n eliminate_factors=[\"Complex pricing models\", \"Long implementation times\"],\n reduce_factors=[\"Customer acquisition cost\", \"Feature complexity\"],\n raise_factors=[\"User experience quality\", \"Customer support\"],\n create_factors=[\"Self-service capabilities\", \"Industry-specific solutions\"],\n value_innovation_opportunities=[\n {\"opportunity\": \"Vertical-specific solution\", \"impact\": \"high\", \"feasibility\": \"medium\"},\n {\"opportunity\": \"Freemium model\", \"impact\": \"medium\", \"feasibility\": \"high\"}\n ],\n new_market_spaces=[\"Underserved SMB segment\", \"Industry-specific verticals\"]\n ),\n growth_scenarios=[\n GrowthScenario(\n name=\"Conservative\",\n description=\"Focus on existing market with incremental improvements\",\n revenue_projection_3yr=revenue * 3,\n investment_required=revenue * 0.5,\n key_milestones=[\"10% market share\", \"EBITDA positive\"],\n risks=[\"Slow growth\", \"Competitor advances\"],\n probability_of_success=80\n ),\n GrowthScenario(\n name=\"Moderate\",\n description=\"Balanced growth through market and product expansion\",\n revenue_projection_3yr=revenue * 5,\n investment_required=revenue * 1,\n key_milestones=[\"New market entry\", \"Product suite launch\"],\n risks=[\"Execution complexity\", \"Resource constraints\"],\n probability_of_success=60\n ),\n GrowthScenario(\n name=\"Aggressive\",\n description=\"Rapid expansion through multiple initiatives\",\n revenue_projection_3yr=revenue * 10,\n investment_required=revenue * 2,\n key_milestones=[\"Market leadership\", \"International expansion\"],\n risks=[\"High burn rate\", \"Quality issues\"],\n probability_of_success=40\n )\n ],\n recommended_direction=\"Pursue moderate growth strategy balancing market penetration with selective product enhancements. This optimizes risk-return profile while building sustainable competitive advantages.\"\n )\n\nasync def analyze_phase3_implementation(startup_data: Dict[str, Any], phase2_results: Phase2Analysis) -> Phase3Analysis:\n \"\"\"Phase 3: How to Get There? - Implementation roadmap\"\"\"\n \n revenue = startup_data.get('annual_revenue_run_rate', 0)\n team_size = startup_data.get('team_size_full_time', 5)\n burn_rate = startup_data.get('monthly_burn_usd', 50000)\n \n prompt = f\"\"\"\n Based on Phase 2 recommendation of {phase2_results.recommended_direction}, create Phase 3 implementation plan:\n - Current Revenue: ${revenue:,.0f}\n - Team Size: {team_size}\n - Burn Rate: ${burn_rate:,.0f}/month\n - Chosen Strategy: {phase2_results.ansoff_matrix.recommended_strategy}\n \n Provide detailed implementation plan using:\n 1. Balanced Scorecard (4 perspectives with specific KPIs)\n 2. OKR Framework (quarterly objectives and key results)\n 3. Resource Requirements (people, money, technology, partnerships)\n 4. Risk Mitigation Plan (top 5 risks with mitigation strategies)\n 5. Success Metrics (leading and lagging indicators)\n \n Return valid JSON matching this structure:\n {{\n \"implementation_roadmap_summary\": \"2-3 paragraph executive summary of implementation plan\",\n \"balanced_scorecard\": [\n {{\n \"perspective\": \"Financial\",\n \"objectives\": [\"objective1\", \"objective2\"],\n \"measures\": [\"measure1\", \"measure2\"],\n \"targets\": [\"target1\", \"target2\"],\n \"initiatives\": [\"initiative1\", \"initiative2\"]\n }},\n {{\n \"perspective\": \"Customer\",\n \"objectives\": [\"objective1\", \"objective2\"],\n \"measures\": [\"measure1\", \"measure2\"],\n \"targets\": [\"target1\", \"target2\"],\n \"initiatives\": [\"initiative1\", \"initiative2\"]\n }},\n {{\n \"perspective\": \"Internal Process\",\n \"objectives\": [\"objective1\", \"objective2\"],\n \"measures\": [\"measure1\", \"measure2\"],\n \"targets\": [\"target1\", \"target2\"],\n \"initiatives\": [\"initiative1\", \"initiative2\"]\n }},\n {{\n \"perspective\": \"Learning & Growth\",\n \"objectives\": [\"objective1\", \"objective2\"],\n \"measures\": [\"measure1\", \"measure2\"],\n \"targets\": [\"target1\", \"target2\"],\n \"initiatives\": [\"initiative1\", \"initiative2\"]\n }}\n ],\n \"okr_framework\": [\n {{\n \"quarter\": \"Q1 2025\",\n \"objectives\": [\n {{\n \"objective\": \"Achieve product-market fit\",\n \"key_results\": [\n {{\"kr\": \"Reach 100 paying customers\", \"current\": 50, \"target\": 100}},\n {{\"kr\": \"Achieve 90% retention rate\", \"current\": 75, \"target\": 90}},\n {{\"kr\": \"Generate $500K ARR\", \"current\": 250000, \"target\": 500000}}\n ]\n }}\n ]\n }},\n {{\n \"quarter\": \"Q2 2025\",\n \"objectives\": [\n {{\n \"objective\": \"Scale go-to-market\",\n \"key_results\": [\n {{\"kr\": \"Hire 5 sales reps\", \"current\": 2, \"target\": 7}},\n {{\"kr\": \"Launch partner program\", \"current\": 0, \"target\": 10}},\n {{\"kr\": \"Reach $1M ARR\", \"current\": 500000, \"target\": 1000000}}\n ]\n }}\n ]\n }}\n ],\n \"resource_requirements\": {{\n \"human_resources\": [\n {{\"role\": \"VP Sales\", \"level\": \"Senior\", \"timeline\": \"Q1\", \"cost\": 250000}},\n {{\"role\": \"Engineers\", \"count\": 5, \"timeline\": \"Q1-Q2\", \"cost\": 750000}}\n ],\n \"financial_resources\": {{\n \"total_capital_needed\": 5000000,\n \"runway_extension\": 18,\n \"monthly_burn_target\": 150000,\n \"revenue_targets\": {{\"Q1\": 125000, \"Q2\": 250000, \"Q3\": 400000, \"Q4\": 600000}}\n }},\n \"technology_resources\": [\"CRM system\", \"Analytics platform\", \"CI/CD infrastructure\"],\n \"partnership_resources\": [\"Channel partners\", \"Technology integrators\", \"Industry associations\"]\n }},\n \"risk_mitigation_plan\": [\n {{\n \"risk\": \"Customer acquisition costs exceed projections\",\n \"impact\": \"High\",\n \"likelihood\": \"Medium\",\n \"mitigation_strategy\": \"Implement product-led growth features\",\n \"contingency_plan\": \"Reduce paid marketing, focus on organic channels\"\n }},\n {{\n \"risk\": \"Key talent retention\",\n \"impact\": \"High\",\n \"likelihood\": \"Low\",\n \"mitigation_strategy\": \"Competitive compensation packages with equity\",\n \"contingency_plan\": \"Executive search firm on retainer\"\n }}\n ],\n \"success_metrics\": [\n {{\"metric\": \"Monthly Recurring Revenue\", \"type\": \"lagging\", \"target\": \"$100K by Q2\", \"frequency\": \"monthly\"}},\n {{\"metric\": \"Customer Acquisition Cost\", \"type\": \"leading\", \"target\": \"<$1000\", \"frequency\": \"weekly\"}},\n {{\"metric\": \"Net Promoter Score\", \"type\": \"leading\", \"target\": \">50\", \"frequency\": \"quarterly\"}},\n {{\"metric\": \"Runway Months\", \"type\": \"lagging\", \"target\": \">18\", \"frequency\": \"monthly\"}}\n ]\n }}\n \"\"\"\n \n response = await call_deepseek_api(prompt)\n if not response:\n return generate_fallback_phase3_analysis(startup_data)\n \n try:\n data = _extract_json_from_response(response)\n return Phase3Analysis(**data)\n except Exception as e:\n logger.error(f\"Failed to parse Phase 3 analysis: {e}\")\n return generate_fallback_phase3_analysis(startup_data)\n\ndef generate_fallback_phase3_analysis(startup_data: Dict[str, Any]) -> Phase3Analysis:\n \"\"\"Generate fallback Phase 3 analysis if API fails\"\"\"\n \n return Phase3Analysis(\n implementation_roadmap_summary=\"The implementation focuses on achieving product-market fit in Q1, scaling go-to-market in Q2-Q3, and preparing for Series A in Q4. Key success factors include maintaining capital efficiency while accelerating growth.\",\n balanced_scorecard=[\n BalancedScorecardPerspective(\n perspective=\"Financial\",\n objectives=[\"Achieve profitability\", \"Optimize burn rate\"],\n measures=[\"Monthly burn\", \"Revenue growth\"],\n targets=[\"<$100K/month\", \">30% MoM\"],\n initiatives=[\"Cost optimization\", \"Pricing strategy\"]\n ),\n BalancedScorecardPerspective(\n perspective=\"Customer\",\n objectives=[\"Improve satisfaction\", \"Increase retention\"],\n measures=[\"NPS score\", \"Churn rate\"],\n targets=[\">50\", \"<5%\"],\n initiatives=[\"Customer success program\", \"Product improvements\"]\n ),\n BalancedScorecardPerspective(\n perspective=\"Internal Process\",\n objectives=[\"Streamline operations\", \"Improve efficiency\"],\n measures=[\"Cycle time\", \"Automation rate\"],\n targets=[\"<2 days\", \">80%\"],\n initiatives=[\"Process automation\", \"Tool implementation\"]\n ),\n BalancedScorecardPerspective(\n perspective=\"Learning & Growth\",\n objectives=[\"Build team capabilities\", \"Foster innovation\"],\n measures=[\"Training hours\", \"Innovation index\"],\n targets=[\">40 hrs/year\", \">8/10\"],\n initiatives=[\"Training program\", \"Innovation labs\"]\n )\n ],\n okr_framework=[\n OKRSet(\n quarter=\"Q1 2025\",\n objectives=[\n {\n \"objective\": \"Achieve product-market fit\",\n \"key_results\": [\n {\"kr\": \"100 paying customers\", \"current\": 50, \"target\": 100},\n {\"kr\": \"90% retention rate\", \"current\": 75, \"target\": 90}\n ]\n }\n ]\n ),\n OKRSet(\n quarter=\"Q2 2025\",\n objectives=[\n {\n \"objective\": \"Scale revenue\",\n \"key_results\": [\n {\"kr\": \"$1M ARR\", \"current\": 500000, \"target\": 1000000},\n {\"kr\": \"5 enterprise deals\", \"current\": 1, \"target\": 5}\n ]\n }\n ]\n )\n ],\n resource_requirements=ResourceRequirements(\n human_resources=[\n {\"role\": \"VP Sales\", \"level\": \"Senior\", \"timeline\": \"Q1\", \"cost\": 250000},\n {\"role\": \"Engineers\", \"count\": 5, \"timeline\": \"Q1-Q2\", \"cost\": 750000}\n ],\n financial_resources={\n \"total_capital_needed\": 5000000,\n \"runway_extension\": 18,\n \"monthly_burn_target\": 150000\n },\n technology_resources=[\"Salesforce CRM\", \"Mixpanel Analytics\", \"AWS Infrastructure\"],\n partnership_resources=[\"Channel partners\", \"System integrators\"]\n ),\n risk_mitigation_plan=[\n RiskMitigationItem(\n risk=\"Market competition intensifies\",\n impact=\"High\",\n likelihood=\"Medium\",\n mitigation_strategy=\"Accelerate product differentiation\",\n contingency_plan=\"Focus on niche market segment\"\n ),\n RiskMitigationItem(\n risk=\"Funding environment deteriorates\",\n impact=\"High\",\n likelihood=\"Low\",\n mitigation_strategy=\"Extend runway, improve unit economics\",\n contingency_plan=\"Bridge financing from existing investors\"\n )\n ],\n success_metrics=[\n {\"metric\": \"ARR\", \"type\": \"lagging\", \"target\": \"$2M by year-end\", \"frequency\": \"monthly\"},\n {\"metric\": \"CAC Payback\", \"type\": \"leading\", \"target\": \"<12 months\", \"frequency\": \"monthly\"},\n {\"metric\": \"Employee NPS\", \"type\": \"leading\", \"target\": \">70\", \"frequency\": \"quarterly\"}\n ]\n )\n\n@michelin_router.post(\"/strategic-analysis\", response_model=MichelinAnalysisResponse)\nasync def perform_michelin_analysis(request: MichelinAnalysisRequest):\n \"\"\"Perform complete Michelin 3-phase strategic analysis\"\"\"\n \n try:\n startup_data = request.startup_data\n company_name = startup_data.get('company_name', 'Startup')\n \n # Execute all three phases\n logger.info(\"Starting Phase 1 analysis...\")\n phase1 = await analyze_phase1_current_state(startup_data)\n \n logger.info(\"Starting Phase 2 analysis...\")\n phase2 = await analyze_phase2_strategic_direction(startup_data, phase1)\n \n logger.info(\"Starting Phase 3 analysis...\")\n phase3 = await analyze_phase3_implementation(startup_data, phase2)\n \n # Generate executive briefing\n executive_briefing = f\"\"\"\n {company_name} is positioned as a {phase1.bcg_matrix.position} in its market with significant growth potential. \n The recommended strategic direction is {phase2.recommended_direction}. \n Implementation will require ${phase3.resource_requirements.financial_resources.get('total_capital_needed', 5000000):,.0f} \n in capital and focus on {phase3.okr_framework[0].objectives[0]['objective']} as the immediate priority.\n \n The company faces {phase1.porters_five_forces.overall_industry_attractiveness} industry attractiveness \n but can leverage its {phase1.swot_analysis.strengths[0]['item']} to capture market opportunity.\n Success hinges on executing the {phase2.ansoff_matrix.recommended_strategy} strategy while \n maintaining capital efficiency and achieving key milestones.\n \"\"\"\n \n # Extract key recommendations\n key_recommendations = [\n f\"Focus on {phase2.ansoff_matrix.recommended_strategy} as primary growth strategy\",\n f\"Target {phase3.okr_framework[0].objectives[0]['key_results'][0]['kr']}\",\n f\"Implement {phase3.balanced_scorecard[0].initiatives[0]} to improve financial performance\",\n f\"Mitigate '{phase3.risk_mitigation_plan[0].risk}' through {phase3.risk_mitigation_plan[0].mitigation_strategy}\"\n ]\n \n # Define critical success factors\n critical_success_factors = [\n \"Achieve product-market fit within 6 months\",\n \"Maintain burn rate below target while scaling\",\n \"Build competitive moats through differentiation\",\n \"Secure Series A funding within 12 months\"\n ]\n \n # Create next steps\n next_steps = [\n {\n \"timeline\": \"30 days\",\n \"actions\": [\n \"Finalize strategic plan with board approval\",\n \"Begin recruitment for key positions\",\n \"Launch first strategic initiative\"\n ]\n },\n {\n \"timeline\": \"60 days\",\n \"actions\": [\n \"Complete team scaling for Q1\",\n \"Implement new processes and systems\",\n \"Achieve first OKR milestone\"\n ]\n },\n {\n \"timeline\": \"90 days\",\n \"actions\": [\n \"Review Q1 performance against targets\",\n \"Adjust strategy based on learnings\",\n \"Prepare for next funding round\"\n ]\n }\n ]\n \n return MichelinAnalysisResponse(\n company_name=company_name,\n analysis_date=datetime.now().isoformat(),\n executive_briefing=executive_briefing.strip(),\n phase1=phase1,\n phase2=phase2,\n phase3=phase3,\n key_recommendations=key_recommendations,\n critical_success_factors=critical_success_factors,\n next_steps=next_steps\n )\n \n except Exception as e:\n logger.error(f\"Michelin analysis failed: {e}\")\n raise HTTPException(status_code=500, detail=str(e))\n\n@michelin_router.get(\"/status\")\nasync def check_michelin_status():\n \"\"\"Check if Michelin analysis service is available\"\"\"\n return {\n \"status\": \"operational\",\n \"framework_analysis_available\": FRAMEWORK_ANALYSIS_AVAILABLE,\n \"deepseek_configured\": bool(DEEPSEEK_API_KEY),\n \"version\": \"1.0.0\"\n }\n\n# Shutdown handler for cleanup\nasync def shutdown_michelin_engine():\n \"\"\"Cleanup resources on shutdown\"\"\"\n logger.info(\"Shutting down Michelin analysis engine\")\n # Add any cleanup code here if needed"}}, "test_direct_api.py": {"ab889d31a3dfb15b6d06aced0cc9df8df600a068": {"t": 1785747500.2086, "n": 1262, "h": "25b64316b4f8f10e", "c": "#\\!/usr/bin/env python3\nimport asyncio\nimport aiohttp\nimport json\nimport os\n\nasync def test_direct_api():\n url = \"https://api.deepseek.com/v1/chat/completions\"\n api_key = os.getenv(\"DEEPSEEK_API_KEY\", \"sk-f68b7148243e4663a31386a5ea6093cf\")\n \n headers = {\n \"Authorization\": f\"Bearer {api_key}\",\n \"Content-Type\": \"application/json\"\n }\n \n prompt = \"\"\"Analyze the competitive position. Return ONLY valid JSON:\n{\n \"position_assessment\": {\n \"overall_rating\": \"Strong/Moderate/Weak\",\n \"summary\": \"Brief summary\"\n }\n}\"\"\"\n \n payload = {\n \"model\": \"deepseek-chat\",\n \"messages\": [\n {\"role\": \"system\", \"content\": \"You are a strategic analyst.\"},\n {\"role\": \"user\", \"content\": prompt}\n ],\n \"temperature\": 0.7,\n \"max_tokens\": 2000\n }\n \n async with aiohttp.ClientSession() as session:\n async with session.post(url, json=payload, headers=headers) as response:\n result = await response.json()\n content = result['choices'][0]['message']['content']\n print(\"Response content:\")\n print(content)\n print(\"\\nLength:\", len(content))\n\nif __name__ == \"__main__\":\n asyncio.run(test_direct_api())\nEOF < /dev/null"}, "9a26feece1b4977fe4d9e9d0965674854d3505bc": {"t": 1785763775.020932, "n": 1262, "h": "25b64316b4f8f10e", "c": "#\\!/usr/bin/env python3\nimport asyncio\nimport aiohttp\nimport json\nimport os\n\nasync def test_direct_api():\n url = \"https://api.deepseek.com/v1/chat/completions\"\n api_key = os.getenv(\"DEEPSEEK_API_KEY\", \"sk-f68b7148243e4663a31386a5ea6093cf\")\n \n headers = {\n \"Authorization\": f\"Bearer {api_key}\",\n \"Content-Type\": \"application/json\"\n }\n \n prompt = \"\"\"Analyze the competitive position. Return ONLY valid JSON:\n{\n \"position_assessment\": {\n \"overall_rating\": \"Strong/Moderate/Weak\",\n \"summary\": \"Brief summary\"\n }\n}\"\"\"\n \n payload = {\n \"model\": \"deepseek-chat\",\n \"messages\": [\n {\"role\": \"system\", \"content\": \"You are a strategic analyst.\"},\n {\"role\": \"user\", \"content\": prompt}\n ],\n \"temperature\": 0.7,\n \"max_tokens\": 2000\n }\n \n async with aiohttp.ClientSession() as session:\n async with session.post(url, json=payload, headers=headers) as response:\n result = await response.json()\n content = result['choices'][0]['message']['content']\n print(\"Response content:\")\n print(content)\n print(\"\\nLength:\", len(content))\n\nif __name__ == \"__main__\":\n asyncio.run(test_direct_api())\nEOF < /dev/null"}}}} |