"""
Optimus Research Center - FastAPI Main Application Entrypoint
Version 1.1.0 (Standalone & Independent Architecture)
No connection to Digital Optimus.
"""

import os
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware

from app.config import settings
from app.core.database import init_db
from app.core.coordinator import ScientificCoordinator
from app.lab_algorithms.router import router as algo_router
from app.lab_ai.router import router as ai_router
from app.core.coordinator_router import router as coord_router


@asynccontextmanager
async def lifespan(app: FastAPI):
    # 1. Write server.pid for safe process identification
    pid_file = settings.storage_path / "server.pid"
    try:
        pid_file.write_text(str(os.getpid()))
    except Exception:
        pass

    # 2. Initialize DB schema
    init_db()

    # 3. Reconcile any crashed/interrupted tasks from prior run
    coord = ScientificCoordinator()
    recovered = coord.recover_interrupted_tasks()
    if recovered:
        print(f"[RECOVERY] Reconciled {len(recovered)} interrupted task(s) from previous session.")

    print("=" * 70)
    print(f"   OPTIMUS RESEARCH CENTER - VERSION {settings.VERSION} (STANDALONE)")
    print("   Status: Operational | Environment: Independent")
    print(f"   Listening on: http://{settings.HOST}:{settings.PORT}")
    print("   Digital Optimus Connection: STRICTLY DISABLED")
    print("=" * 70)

    yield

    # Clean up server.pid on shutdown
    try:
        if pid_file.exists():
            pid_file.unlink()
    except Exception:
        pass

    print("[SHUTDOWN] Optimus Research Center stopped gracefully.")


app = FastAPI(
    title=settings.PROJECT_NAME,
    version=settings.VERSION,
    description="Independent dual-laboratory scientific research technology center.",
    lifespan=lifespan
)

# CORS restricted strictly to verified local origins
local_origins = [
    f"http://{settings.HOST}:{settings.PORT}",
    f"http://localhost:{settings.PORT}",
    f"http://127.0.0.1:{settings.PORT}",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=local_origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)

# Routers
app.include_router(algo_router)
app.include_router(ai_router)
app.include_router(coord_router)

# Mount static assets
static_dir = Path(__file__).resolve().parent / "static"
if static_dir.exists():
    app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")


@app.get("/", response_class=HTMLResponse)
async def serve_index():
    index_file = static_dir / "index.html"
    if index_file.exists():
        with open(index_file, "r", encoding="utf-8") as f:
            return HTMLResponse(content=f.read())
    return HTMLResponse("<h1>Optimus Research Center</h1><p>Static UI not loaded.</p>")


@app.get("/health")
def health_check():
    return {
        "status": "HEALTHY",
        "version": settings.VERSION,
        "packager_version": settings.PACKAGER_VERSION,
        "protocol_version": settings.PROTOCOL_VERSION,
        "profile": settings.ORC_PROFILE,
        "mode": "STANDALONE_V1",
        "digital_optimus_connected": False,
        "titan_connected": settings.TITAN_INTEGRATION_ENABLED,
        "neurolab_connected": settings.NEUROLAB_INTEGRATION_ENABLED
    }
