# be/app/crud/history.py
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlalchemy.orm import selectinload
from typing import List, Optional, Any, Dict

from app.models import ChoreHistory, ChoreAssignmentHistory, ChoreHistoryEventTypeEnum, User, Chore, Group
from app.schemas.chore import ChoreHistoryPublic, ChoreAssignmentHistoryPublic

async def create_chore_history_entry(
    db: AsyncSession,
    *,
    chore_id: Optional[int],
    group_id: Optional[int],
    changed_by_user_id: Optional[int],
    event_type: ChoreHistoryEventTypeEnum,
    event_data: Optional[Dict[str, Any]] = None,
) -> ChoreHistory:
    """Logs an event in the chore history."""
    history_entry = ChoreHistory(
        chore_id=chore_id,
        group_id=group_id,
        changed_by_user_id=changed_by_user_id,
        event_type=event_type,
        event_data=event_data or {},
    )
    db.add(history_entry)
    await db.flush()
    await db.refresh(history_entry)
    return history_entry

async def create_assignment_history_entry(
    db: AsyncSession,
    *,
    assignment_id: int,
    changed_by_user_id: int,
    event_type: ChoreHistoryEventTypeEnum,
    event_data: Optional[Dict[str, Any]] = None,
) -> ChoreAssignmentHistory:
    """Logs an event in the chore assignment history."""
    history_entry = ChoreAssignmentHistory(
        assignment_id=assignment_id,
        changed_by_user_id=changed_by_user_id,
        event_type=event_type,
        event_data=event_data or {},
    )
    db.add(history_entry)
    await db.flush()
    await db.refresh(history_entry)
    return history_entry

async def get_chore_history(db: AsyncSession, chore_id: int) -> List[ChoreHistory]:
    """Gets all history for a specific chore."""
    result = await db.execute(
        select(ChoreHistory)
        .where(ChoreHistory.chore_id == chore_id)
        .options(selectinload(ChoreHistory.changed_by_user))
        .order_by(ChoreHistory.timestamp.desc())
    )
    return result.scalars().all()

async def get_assignment_history(db: AsyncSession, assignment_id: int) -> List[ChoreAssignmentHistory]:
    """Gets all history for a specific assignment."""
    result = await db.execute(
        select(ChoreAssignmentHistory)
        .where(ChoreAssignmentHistory.assignment_id == assignment_id)
        .options(selectinload(ChoreAssignmentHistory.changed_by_user))
        .order_by(ChoreAssignmentHistory.timestamp.desc())
    )
    return result.scalars().all()

async def get_group_chore_history(db: AsyncSession, group_id: int) -> List[ChoreHistory]:
    """Gets all chore-related history for a group, including chore-specific and group-level events."""
    result = await db.execute(
        select(ChoreHistory)
        .where(ChoreHistory.group_id == group_id)
        .options(
            selectinload(ChoreHistory.changed_by_user),
            selectinload(ChoreHistory.chore) # Also load chore info if available
        )
        .order_by(ChoreHistory.timestamp.desc())
    )
    return result.scalars().all() 