# ARCHITECTURE DESIGNER V2 - TECHNOLOGY-SPECIFIC SPECIALISTS
# Main FastAPI application with technology routing

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 technology specialists
from core.router import TechnologyRouter
from core.combiner import ArchitectureCombiner
from models.request_models import ArchitectureDesignRequest
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 - Technology Specialists",
    description="Technology-specific architecture design with React, Node.js, PostgreSQL specialists",
    version="2.0.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",
        "version": "2.0.0",
        "specialists": {
            "frontend": ["React"],
            "backend": ["Node.js"],
            "database": ["PostgreSQL"]
        },
        "features": {
            "technology_specific_design": True,
            "expert_level_architecture": True,
            "claude_ai_powered": True,
            "100_percent_implementation_ready": True
        }
    }

@app.post("/api/v1/design-architecture")
async def design_architecture(request: ArchitectureDesignRequest):
    """Design complete architecture using technology-specific specialists"""
    try:
        project_id = str(uuid.uuid4())
        
        logger.info("🏗️ Starting technology-specific architecture design")
        logger.info(f"   Project ID: {project_id}")
        
        # Extract technology stack from tech-stack-selector output
        tech_stack = technology_router.extract_technology_stack(
            request.tech_stack_recommendations
        )
        
        logger.info(f"   Frontend: {tech_stack.frontend_framework}")
        logger.info(f"   Backend: {tech_stack.backend_language}")
        logger.info(f"   Database: {tech_stack.database_system}")
        
        # Route to technology-specific specialists
        design_results = await technology_router.route_to_specialists(
            tech_stack=tech_stack,
            functional_requirements=request.tech_stack_recommendations.get('functional_requirements', {}),
            business_context=request.tech_stack_recommendations.get('claude_recommendations', {})
        )
        
        # Combine specialist outputs into unified architecture
        combined_architecture = architecture_combiner.combine_architecture_outputs(
            frontend_result=design_results['frontend'],
            backend_result=design_results['backend'],
            database_result=design_results['database'],
            tech_stack=tech_stack
        )
        
        # Build final response
        response = {
            "success": True,
            "project_metadata": {
                "project_id": project_id,
                "project_name": request.tech_stack_recommendations.get('functional_requirements', {}).get('feature_name', 'Unknown Project'),
                "complexity": request.tech_stack_recommendations.get('functional_requirements', {}).get('complexity_level', 'medium'),
                "technology_specialists_used": {
                    "frontend": tech_stack.frontend_framework,
                    "backend": tech_stack.backend_language,
                    "database": tech_stack.database_system
                },
                "architecture_generated_at": datetime.utcnow().isoformat()
            },
            "technology_specifications": tech_stack.__dict__,
            "architecture_design": combined_architecture,
            "code_generation_ready": {
                "ready_for_generation": True,
                "implementation_complete": True,
                "technology_specific": True,
                "specialist_designed": True
            }
        }
        
        logger.info("✅ Technology-specific architecture design completed")
        return response
        
    except Exception as e:
        logger.error(f"❌ Architecture design failed: {e}")
        raise HTTPException(status_code=500, detail=f"Architecture design failed: {str(e)}")

if __name__ == "__main__":
    import uvicorn
    
    logger.info("="*80)
    logger.info("🏗️ ARCHITECTURE DESIGNER v2.0 - TECHNOLOGY SPECIALISTS")
    logger.info("="*80)
    logger.info("✅ React Frontend Specialist")
    logger.info("✅ Node.js Backend Specialist") 
    logger.info("✅ PostgreSQL Database Specialist")
    logger.info("✅ 100% Implementation Ready")
    logger.info("✅ Claude AI Powered")
    logger.info("="*80)
    
    uvicorn.run("main:app", host="0.0.0.0", port=8003, log_level="info")
