# FIXED ARCHITECTURE DESIGNER V2 - Correctly integrates with YOUR tech-stack-selector
# Fixed to work with your exact response structure

import os
import sys
import json
import uuid
from datetime import datetime
from typing import Dict, Any, Optional
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger

# Import our FIXED technology router
from core.router import TechnologyRouter
from core.combiner import ArchitectureCombiner
from config.settings import Settings

# Configure logging
logger.remove()
logger.add(sys.stdout, level="INFO", format="{time} | {level} | {message}")

# Initialize settings
settings = Settings()

app = FastAPI(
    title="Architecture Designer v2 - FIXED for Tech-Stack-Selector v11",
    description="Fixed integration with your tech-stack-selector response format",
    version="2.1.0"
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize core components
technology_router = TechnologyRouter()
architecture_combiner = ArchitectureCombiner()

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "service": "architecture-designer-v2-fixed",
        "version": "2.1.0",
        "integration": "tech-stack-selector-v11",
        "specialists": {
            "frontend": ["React"],
            "backend": ["Node.js"],
            "database": ["PostgreSQL"]
        },
        "features": {
            "tech_stack_selector_integration": True,
            "correct_response_parsing": True,
            "claude_ai_powered": True,
            "production_ready": True
        }
    }

@app.post("/api/v1/design-architecture")
async def design_architecture(request: Request):
    """
    FIXED endpoint that correctly processes YOUR tech-stack-selector response
    
    Expected input: Complete response from tech-stack-selector v11
    """
    try:
        # Get the complete tech-stack-selector response
        tech_stack_selector_response = await request.json()
        
        project_id = str(uuid.uuid4())
        
        logger.info("🏗️ FIXED Architecture Designer starting...")
        logger.info(f"   Project ID: {project_id}")
        logger.info(f"   Tech-Stack-Selector Response Keys: {list(tech_stack_selector_response.keys())}")
        
        # Validate we have the expected structure from YOUR tech-stack-selector
        if not tech_stack_selector_response.get('success'):
            raise HTTPException(
                status_code=400, 
                detail="Invalid tech-stack-selector response: missing 'success' field"
            )
        
        if 'claude_recommendations' not in tech_stack_selector_response:
            raise HTTPException(
                status_code=400,
                detail="Invalid tech-stack-selector response: missing 'claude_recommendations'"
            )
        
        if 'functional_requirements' not in tech_stack_selector_response:
            raise HTTPException(
                status_code=400,
                detail="Invalid tech-stack-selector response: missing 'functional_requirements'"
            )
        
        # Use the FIXED router to process YOUR tech-stack-selector response
        design_results = await technology_router.route_and_design(
            tech_stack_selector_response, project_id
        )
        
        # Extract project info from YOUR response structure
        functional_reqs = tech_stack_selector_response.get('functional_requirements', {})
        project_context = tech_stack_selector_response.get('project_context', {})
        
        # Build response in the format YOUR frontend expects
        response = {
            "success": True,
            "project_metadata": {
                "project_id": project_id,
                "project_name": functional_reqs.get('feature_name', 'AI Generated Project'),
                "complexity": functional_reqs.get('complexity_level', 'medium'),
                "technology_specialists_used": design_results.get('technologies_used', {}),
                "architecture_generated_at": datetime.utcnow().isoformat(),
                "source_data": "tech_stack_selector_v11"
            },
            "technology_specifications": design_results.get('technology_specifications', {}),
            "architecture_design": design_results.get('architecture_design', {}),
            "code_generation_ready": {
                "frontend_ready": design_results['specialist_results']['frontend'].get('success', False),
                "backend_ready": design_results['specialist_results']['backend'].get('success', False),
                "database_ready": design_results['specialist_results']['database'].get('success', False),
                "integration_ready": design_results.get('integration_ready', False),
                "implementation_complete": True,
                "ai_generated": True
            },
            # Include original tech-stack-selector data for reference
            "original_tech_stack_data": {
                "functional_requirements": functional_reqs,
                "project_context": project_context,
                "claude_recommendations": tech_stack_selector_response.get('claude_recommendations', {})
            }
        }
        
        logger.info("✅ FIXED Architecture design completed successfully")
        logger.info(f"   Frontend: {design_results['technologies_used']['frontend']}")
        logger.info(f"   Backend: {design_results['technologies_used']['backend']}")
        logger.info(f"   Database: {design_results['technologies_used']['database']}")
        
        return response
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ Architecture design failed: {e}")
        logger.error(f"   Request data keys: {list((await request.json()).keys()) if hasattr(request, 'json') else 'unknown'}")
        raise HTTPException(
            status_code=500, 
            detail=f"Architecture design failed: {str(e)}"
        )

@app.post("/api/v1/debug/analyze-request")
async def debug_analyze_request(request: Request):
    """Debug endpoint to analyze incoming requests from tech-stack-selector"""
    try:
        request_data = await request.json()
        
        analysis = {
            "request_keys": list(request_data.keys()),
            "has_success": "success" in request_data,
            "success_value": request_data.get("success"),
            "has_claude_recommendations": "claude_recommendations" in request_data,
            "has_functional_requirements": "functional_requirements" in request_data,
            "claude_recommendations_keys": list(request_data.get("claude_recommendations", {}).keys()),
            "functional_requirements_keys": list(request_data.get("functional_requirements", {}).keys()),
            "sample_tech_path": None,
            "technology_structure": None
        }
        
        # Try to find technology recommendations
        claude_recs = request_data.get("claude_recommendations", {})
        if "technology_recommendations" in claude_recs:
            tech_recs = claude_recs["technology_recommendations"]
            analysis["sample_tech_path"] = "claude_recommendations.technology_recommendations"
            analysis["technology_structure"] = {
                "frontend": tech_recs.get("frontend", {}),
                "backend": tech_recs.get("backend", {}),
                "database": tech_recs.get("database", {})
            }
        
        return {
            "analysis": analysis,
            "recommendations": {
                "structure_valid": analysis["has_success"] and analysis["has_claude_recommendations"],
                "can_extract_technologies": analysis["technology_structure"] is not None,
                "ready_for_architecture": analysis["has_functional_requirements"]
            }
        }
        
    except Exception as e:
        return {"error": str(e), "debug": "Failed to analyze request"}

if __name__ == "__main__":
    import uvicorn
    
    logger.info("="*80)
    logger.info("🏗️ ARCHITECTURE DESIGNER v2.1 - FIXED FOR TECH-STACK-SELECTOR v11")
    logger.info("="*80)
    logger.info("✅ FIXED: Correct response parsing from tech-stack-selector")
    logger.info("✅ FIXED: Technology extraction and routing")
    logger.info("✅ FIXED: Functional requirements integration")
    logger.info("✅ React Frontend Specialist")
    logger.info("✅ Node.js Backend Specialist") 
    logger.info("✅ PostgreSQL Database Specialist")
    logger.info("="*80)
    
    uvicorn.run("main:app", host="0.0.0.0", port=8003, log_level="info")