from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import httpx
import logging

app = FastAPI()


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


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class ContactForm(BaseModel):
    name: str
    email: str
    message: str
missions = [
    {"date": "2025-09-13", "mission": "OrbitSync-1", "status": "Active"},
    {"date": "2025-08-15", "mission": "StarLink-2", "status": "Completed"},
    {"date": "2025-07-20", "mission": "MoonScan", "status": "Pending"}

@app.get("/api/missions")
async def get_missions():
    try:
        async with httpx.AsyncClient() as client:
            response = await client.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&count=3")
            response.raise_for_status()
            nasa_data = response.json()
            for i, mission in enumerate(missions):
                if i < len(nasa_data):
                    mission["description"] = nasa_data[i]["explanation"][:100] + "..."
        return missions
    except httpx.RequestException as e:
        logger.error(f"Error fetching missions: {e}")
        raise HTTPException(status_code=500, detail="Failed to fetch missions")

@app.get("/api/missions/{index}")
async def get_mission_detail(index: int):
    if 0 <= index < len(missions):
        try:
            async with httpx.AsyncClient() as client:
                response = await client.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")
                response.raise_for_status()
                nasa_data = response.json()
                mission = missions[index].copy()
                mission["description"] = nasa_data["explanation"][:200] + "..."
                return mission
        except httpx.RequestException as e:
            logger.error(f"Error fetching mission details: {e}")
            return missions[index]
    raise HTTPException(status_code=404, detail="Mission not found")

@app.get("/api/telemetry")
async def get_telemetry():
    try:
        async with httpx.AsyncClient() as client:
            response = await client.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&count=5")
            response.raise_for_status()
            nasa_data = response.json()
            return {
                "labels": [item["date"] for item in nasa_data],
                "data": [200 + i * 10 for i in range(len(nasa_data))]  
            }
    except httpx.RequestException as e:
        logger.error(f"Error fetching telemetry: {e}")
        return {
            "labels": ["09:00", "09:15", "09:30", "09:45", "10:00"],
            "data": [250, 260, 255, 270, 265]
        }

@app.post("/api/contact")
async def submit_contact(form: ContactForm):
    logger.info(f"Contact form submission: {form.dict()}")
    return {"success": True, "message": "Submission received!"}
    
@app.get("/health")
async def health_check():
    return {"status": "healthy"}