#!/usr/bin/env python3

import asyncio
import logging
import sys
import uuid
from datetime import date, datetime
from typing import Dict, List, Optional

from fastapi import Depends, FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from enum import Enum

app = FastAPI(title="Simplified Calendar Service", version="1.0.0")

# Setup logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

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

# Models and Schemas
class EntryType(str, Enum):
    PERIOD = "period"
    OVULATION = "ovulation"
    SYMPTOMS = "symptoms"
    MEDICATION = "medication"
    MOOD = "mood"
    EXERCISE = "exercise"
    APPOINTMENT = "appointment"

class FlowIntensity(str, Enum):
    LIGHT = "light"
    MEDIUM = "medium"
    HEAVY = "heavy"
    SPOTTING = "spotting"

class MoodType(str, Enum):
    HAPPY = "happy"
    SAD = "sad"
    ANXIOUS = "anxious"
    IRRITATED = "irritated"
    ENERGETIC = "energetic"
    TIRED = "tired"

class CalendarEntryBase(BaseModel):
    entry_date: date
    entry_type: EntryType
    flow_intensity: Optional[FlowIntensity] = None
    period_symptoms: Optional[str] = Field(None, max_length=500)
    mood: Optional[MoodType] = None
    energy_level: Optional[int] = Field(None, ge=1, le=5)
    sleep_hours: Optional[int] = Field(None, ge=0, le=24)
    symptoms: Optional[str] = Field(None, max_length=1000)
    medications: Optional[str] = Field(None, max_length=500)
    notes: Optional[str] = Field(None, max_length=1000)

class CalendarEntryCreate(CalendarEntryBase):
    pass

class CalendarEntryResponse(BaseModel):
    id: int
    uuid: str
    entry_date: date
    entry_type: str
    flow_intensity: Optional[str]
    period_symptoms: Optional[str]
    mood: Optional[str]
    energy_level: Optional[int]
    sleep_hours: Optional[int]
    symptoms: Optional[str]
    medications: Optional[str]
    notes: Optional[str]
    is_predicted: bool
    confidence_score: Optional[int]
    created_at: datetime

# Mock database
calendar_entries = []
entry_id_counter = 1

# Mock authentication
async def get_current_user():
    return {"user_id": 29, "email": "test2@example.com"}

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {"status": "healthy", "service": "calendar_service_simplified"}

@app.post("/api/v1/calendar/entries", response_model=CalendarEntryResponse, status_code=201)
async def create_calendar_entry(entry_data: CalendarEntryCreate):
    """Create a new calendar entry"""
    global entry_id_counter
    
    logger.debug(f"Received entry data: {entry_data}")
    
    # Simulate database entry creation
    new_entry = {
        "id": entry_id_counter,
        "uuid": str(uuid.uuid4()),
        "user_id": 29,  # Mock user ID
        "entry_date": entry_data.entry_date,
        "entry_type": entry_data.entry_type.value,
        "flow_intensity": entry_data.flow_intensity.value if entry_data.flow_intensity else None,
        "period_symptoms": entry_data.period_symptoms,
        "mood": entry_data.mood.value if entry_data.mood else None,
        "energy_level": entry_data.energy_level,
        "sleep_hours": entry_data.sleep_hours,
        "symptoms": entry_data.symptoms,
        "medications": entry_data.medications,
        "notes": entry_data.notes,
        "is_predicted": False,
        "confidence_score": None,
        "created_at": datetime.now(),
    }
    
    calendar_entries.append(new_entry)
    entry_id_counter += 1
    
    logger.debug(f"Created entry with ID: {new_entry['id']}")
    
    # Convert dictionary to CalendarEntryResponse model
    return CalendarEntryResponse(**new_entry)

@app.get("/api/v1/calendar/entries", response_model=List[CalendarEntryResponse])
async def get_calendar_entries():
    """Get all calendar entries"""
    return [CalendarEntryResponse(**entry) for entry in calendar_entries]

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8888)  # Using a different port