from __future__ import annotations

from fastapi import APIRouter, Depends
from pydantic import BaseModel
from typing import Optional, Dict, Any

from ...auth_security import require_admin, require_account
from ...db import get_session
from sqlalchemy.ext.asyncio import AsyncSession

from ...intelligence.decision_logger import DecisionLogger
from ...intelligence.bandit_repo import BanditRepo
from ...intelligence.policy_store import PolicyStore
from ...services.learning_pipeline import LearningPipeline


router = APIRouter(prefix="/api/v2/intelligence", tags=["Intelligence"])


class ResyncBody(BaseModel):
    account_id: Optional[str] = None
    segment: Optional[str] = None
    lookback_days: int = 30


@router.post("/learn/resync", dependencies=[Depends(require_admin)])
async def learn_resync(
    body: ResyncBody,
    db: AsyncSession = Depends(get_session),
    account: str = Depends(require_account),
) -> Dict[str, Any]:
    account_id = body.account_id or account
    # Assemble pipeline components
    decision_logger = DecisionLogger()
    bandits = BanditRepo()
    policies = PolicyStore(db)
    pipeline = LearningPipeline(decision_logger, bandits, policies)

    result = await pipeline.update_from_feedback(
        account_id=str(account_id),
        segment=body.segment,
        lookback_days=body.lookback_days,
    )
    return result
