from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import Column, Integer, String, Text, DateTime
from datetime import datetime
from app.database import get_db, Base
from pydantic import BaseModel
from typing import Optional

router = APIRouter(prefix="/api/annotations", tags=["annotations"])


class AnnotationGantt(Base):
    __tablename__ = "annotations_gantt"
    id = Column(Integer, primary_key=True, index=True)
    operateur_id = Column(Integer, nullable=True)
    date_debut = Column(String(10), nullable=False)
    date_fin = Column(String(10), nullable=False)
    texte = Column(Text, nullable=False)
    couleur = Column(String(20), default='#6b7280')
    date_creation = Column(DateTime, default=datetime.utcnow)


class AnnotationCreate(BaseModel):
    operateur_id: Optional[int] = None
    date_debut: str
    date_fin: str
    texte: str
    couleur: Optional[str] = '#6b7280'


class AnnotationUpdate(BaseModel):
    operateur_id: Optional[int] = None
    date_debut: Optional[str] = None
    date_fin: Optional[str] = None
    texte: Optional[str] = None
    couleur: Optional[str] = None


def _fmt(a):
    return {
        "id": a.id,
        "operateur_id": a.operateur_id,
        "date_debut": a.date_debut,
        "date_fin": a.date_fin,
        "texte": a.texte,
        "couleur": a.couleur,
    }


@router.get("/")
def get_annotations(db: Session = Depends(get_db)):
    return [_fmt(a) for a in db.query(AnnotationGantt).all()]


@router.post("/", status_code=201)
def create_annotation(data: AnnotationCreate, db: Session = Depends(get_db)):
    a = AnnotationGantt(**data.dict())
    db.add(a)
    db.commit()
    db.refresh(a)
    return _fmt(a)


@router.put("/{annotation_id}")
def update_annotation(annotation_id: int, data: AnnotationUpdate, db: Session = Depends(get_db)):
    a = db.query(AnnotationGantt).filter(AnnotationGantt.id == annotation_id).first()
    if not a:
        raise HTTPException(404, "Annotation non trouvée")
    for k, v in data.dict(exclude_none=True).items():
        setattr(a, k, v)
    db.commit()
    db.refresh(a)
    return _fmt(a)


@router.delete("/{annotation_id}")
def delete_annotation(annotation_id: int, db: Session = Depends(get_db)):
    a = db.query(AnnotationGantt).filter(AnnotationGantt.id == annotation_id).first()
    if not a:
        raise HTTPException(404, "Annotation non trouvée")
    db.delete(a)
    db.commit()
    return {"ok": True}
