File size: 3,402 Bytes
04f25f0
 
 
3d93756
04f25f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d93756
c57cfaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
674f2e1
 
c57cfaf
 
 
 
 
 
 
 
 
674f2e1
 
 
 
 
 
 
40fa926
 
674f2e1
 
 
 
 
f72bd53
 
674f2e1
 
 
 
 
 
 
 
 
 
 
c57cfaf
 
 
 
04f25f0
 
 
 
 
 
 
 
0fcc612
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from .api.router import api_router
from .api.debug import router as debug_router

def get_application() -> FastAPI:
    app = FastAPI(
        title="ChatSMITH Backend",
        description="FastAPI backend for ChatSMITH pipeline and auth orchestration",
        version="0.1.0",
    )

    origins = [
        "http://localhost:5173",
        "http://127.0.0.1:5173",
    ]

    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,  # use ["*"] for dev if desired
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    app.include_router(api_router, prefix="/api")
    app.include_router(debug_router, prefix="/api")

    # Serve static files (Frontend)
    import os
    from fastapi.staticfiles import StaticFiles
    from fastapi.responses import FileResponse

    # Determine absolute path to dist folder
    # In Docker (WORKDIR /app), this is /app/frontend/dist
    # Locally, it depends where we run from. We'll rely on relative path from root.
    DIST_DIR = os.path.join(os.getcwd(), "frontend", "dist")

    if os.path.exists(DIST_DIR):
        app.mount("/assets", StaticFiles(directory=os.path.join(DIST_DIR, "assets")), name="assets")
        
        # Catch-all for SPA routing (must be last)
        from fastapi.responses import HTMLResponse
        
        @app.get("/{full_path:path}")
        async def serve_spa(full_path: str):
            # If API request fell through to here, return 404
            if full_path.startswith("api/"):
                return {"detail": "Not Found"}
            
            # Use index.html for all other routes (SPA)
            index_path = os.path.join(DIST_DIR, "index.html")
            if os.path.exists(index_path):
                # READ and INJECT runtime env vars
                try:
                    with open(index_path, "r", encoding="utf-8") as f:
                        content = f.read()
                    
                    # Prepare env vars to inject
                    # Note: We map SECRET env vars to VITE_ PUBLIC vars for the frontend
                    supabase_url = (os.getenv("SUPABASE_URL") or "").strip()
                    supabase_key = (os.getenv("SUPABASE_ANON_KEY") or "").strip()
                    
                    env_script = f"""
                    <script>
                        window.__ENV__ = {{
                            VITE_SUPABASE_URL: "{supabase_url}",
                            VITE_SUPABASE_ANON_KEY: "{supabase_key}",
                            VITE_API_BASE_URL: "/api"
                        }};
                    </script>
                    """
                    
                    # Inject before </head>
                    content = content.replace("</head>", f"{env_script}</head>")
                    return HTMLResponse(content=content)
                except Exception as e:
                    print(f"Error serving SPA: {e}")
                    return FileResponse(index_path) # Fallback
                    
            return {"detail": "Frontend not found (build missing)"}
    else:
        print(f"⚠️ Frontend dist not found at {DIST_DIR}. Serving API only.")

    return app


app = get_application()


@app.get("/health")
def health():
    return {"status": "ok", "version": "debug-v2"}