"""
Policy Management Router
"""
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from pydantic import BaseModel
from datetime import datetime

from app.database import get_db
from app.models.policy import Policy, PolicyStatus
from app.models.user import User
from app.auth.dependencies import get_current_user, RequireAdmin, RequireEditor

router = APIRouter(prefix="/api/v1/policies", tags=["Policies"])

# --- Schemas ---
class PolicyBase(BaseModel):
    name: str
    description: Optional[str] = None
    category: str
    status: PolicyStatus = PolicyStatus.ACTIVE
    critical_sla_days: int = 2
    high_sla_days: int = 7
    medium_sla_days: int = 30
    low_sla_days: int = 90

class PolicyCreate(PolicyBase):
    pass

class PolicyUpdate(BaseModel):
    name: Optional[str] = None
    description: Optional[str] = None
    category: Optional[str] = None
    status: Optional[PolicyStatus] = None
    critical_sla_days: Optional[int] = None
    high_sla_days: Optional[int] = None
    medium_sla_days: Optional[int] = None
    low_sla_days: Optional[int] = None

class PolicyResponse(PolicyBase):
    id: int
    created_at: datetime
    updated_at: datetime
    compliance: Optional[float] = 0.0

    class Config:
        from_attributes = True

# --- Endpoints ---

@router.get("", response_model=List[PolicyResponse])
async def list_policies(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """List all policies"""
    policies = db.query(Policy).all()
    # TODO: Calculate real compliance per policy
    # For now, return mock or simple count (mocking generic 100% for start)
    return policies

@router.post("", response_model=PolicyResponse, status_code=status.HTTP_201_CREATED)
async def create_policy(
    policy_data: PolicyCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(RequireAdmin)
):
    """Create a new policy"""
    policy = Policy(**policy_data.model_dump())
    db.add(policy)
    db.commit()
    db.refresh(policy)
    return policy

@router.put("/{policy_id}", response_model=PolicyResponse)
async def update_policy(
    policy_id: int,
    policy_data: PolicyUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(RequireEditor)
):
    """Update a policy"""
    policy = db.query(Policy).filter(Policy.id == policy_id).first()
    if not policy:
        raise HTTPException(status_code=404, detail="Policy not found")

    for field, value in policy_data.dict(exclude_unset=True).items():
        setattr(policy, field, value)

    db.commit()
    db.refresh(policy)
    return policy

@router.delete("/{policy_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_policy(
    policy_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(RequireAdmin)
):
    """Delete a policy"""
    policy = db.query(Policy).filter(Policy.id == policy_id).first()
    if not policy:
        raise HTTPException(status_code=404, detail="Policy not found")
    
    db.delete(policy)
    db.commit()
    return None
