"""
Team API routes — CRUD for teams, members, draft/main memos,
comments, review flow, and reactions.
"""

import logging
from typing import List

from fastapi import APIRouter, Body, Depends, HTTPException, Request

from common.team.schemas import (
    TeamCreate,
    TeamUpdate,
    TeamResponse,
    TeamMemoCreate,
    TeamMemoResponse,
    TeamCommentCreate,
    TeamCommentResponse,
    ReviewAction,
    ReactionToggle,
    UserProfileResponse,
)
from common.team.services import team_service

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/teams", tags=["teams"])


def get_current_user_id(request: Request) -> str | None:
    return getattr(request.state, "user_id", None)


def require_user(request: Request) -> str:
    user_id = get_current_user_id(request)
    if not user_id:
        raise HTTPException(status_code=401, detail="Authentication required")
    return user_id


# ========================= TEAM CRUD =========================


@router.post("", response_model=TeamResponse, summary="Create team")
async def create_team(request: Request, payload: TeamCreate):
    user_id = require_user(request)
    result = await team_service.create_team(
        name=payload.name,
        description=payload.description,
        owner_id=user_id,
    )
    return result


@router.get("", response_model=List[TeamResponse], summary="List my teams")
async def list_teams(request: Request):
    user_id = require_user(request)
    return await team_service.list_teams(user_id)


@router.get("/{team_id}", response_model=TeamResponse, summary="Get team detail")
async def get_team(request: Request, team_id: str):
    user_id = require_user(request)
    result = await team_service.get_team(team_id, user_id)
    if not result:
        raise HTTPException(status_code=404, detail="Team not found or not a member")
    return result


@router.patch("/{team_id}", response_model=TeamResponse, summary="Update team")
async def update_team(request: Request, team_id: str, payload: TeamUpdate):
    user_id = require_user(request)
    result = await team_service.update_team(
        team_id, user_id,
        name=payload.name,
        description=payload.description,
    )
    if not result:
        raise HTTPException(status_code=403, detail="Not team owner")
    return result


@router.delete("/{team_id}", summary="Delete team")
async def delete_team(request: Request, team_id: str):
    user_id = require_user(request)
    ok = await team_service.delete_team(team_id, user_id)
    if not ok:
        raise HTTPException(status_code=403, detail="Not team owner")
    return {"status": "deleted"}


# ========================= MEMBERS =========================


@router.post("/join", summary="Join team by invite code")
async def join_team(request: Request, invite_code: str = Body(..., embed=True)):
    user_id = require_user(request)
    result = await team_service.join_team(invite_code, user_id)
    if not result:
        raise HTTPException(status_code=404, detail="Invalid invite code")
    return result


@router.get("/{team_id}/members", summary="List team members")
async def list_members(request: Request, team_id: str):
    user_id = require_user(request)
    team = await team_service.get_team(team_id, user_id)
    if not team:
        raise HTTPException(status_code=404, detail="Team not found")
    return {"members": team.get("members", [])}


@router.delete("/{team_id}/members/{target_user_id}", summary="Remove member")
async def remove_member(request: Request, team_id: str, target_user_id: str):
    user_id = require_user(request)
    ok = await team_service.remove_member(team_id, target_user_id, user_id)
    if not ok:
        raise HTTPException(status_code=403, detail="Not owner or can't remove")
    return {"status": "removed"}


@router.post("/{team_id}/leave", summary="Leave team")
async def leave_team(request: Request, team_id: str):
    user_id = require_user(request)
    ok = await team_service.leave_team(team_id, user_id)
    if not ok:
        raise HTTPException(status_code=400, detail="Owner can't leave (delete team instead)")
    return {"status": "left"}


# ========================= USER PROFILES =========================


@router.post("/resolve-users", summary="Batch resolve user IDs to profiles")
async def resolve_users(request: Request, user_ids: List[str] = Body(..., embed=True)):
    require_user(request)
    profiles = await team_service.resolve_user_profiles(user_ids)
    return {"profiles": profiles}


# ========================= TEAM MEMOS (Draft / Main) =========================


@router.post("/{team_id}/memos", response_model=TeamMemoResponse, summary="Create draft memo")
async def create_draft(request: Request, team_id: str, payload: TeamMemoCreate):
    user_id = require_user(request)
    result = await team_service.create_draft(
        team_id, user_id,
        content=payload.content,
        tags=payload.tags,
    )
    if not result:
        raise HTTPException(status_code=403, detail="Not a team member")
    return result


@router.get("/{team_id}/drafts", response_model=List[TeamMemoResponse], summary="List drafts")
async def list_drafts(request: Request, team_id: str):
    user_id = require_user(request)
    return await team_service.list_drafts(team_id, user_id)


@router.get("/{team_id}/main", response_model=List[TeamMemoResponse], summary="List main (merged)")
async def list_main(request: Request, team_id: str):
    user_id = require_user(request)
    return await team_service.list_main(team_id, user_id)


@router.post("/{team_id}/memos/{memo_id}/merge", response_model=TeamMemoResponse, summary="Merge draft → main")
async def merge_memo(request: Request, team_id: str, memo_id: str):
    user_id = require_user(request)
    result = await team_service.merge_to_main(team_id, memo_id, user_id)
    if not result:
        raise HTTPException(status_code=403, detail="Not found or not authorized (owner only)")
    return result


@router.post("/{team_id}/memos/{memo_id}/unmerge", response_model=TeamMemoResponse, summary="Unmerge main → draft")
async def unmerge_memo(request: Request, team_id: str, memo_id: str):
    user_id = require_user(request)
    result = await team_service.unmerge_to_draft(team_id, memo_id, user_id)
    if not result:
        raise HTTPException(status_code=403, detail="Not found or not owner")
    return result


@router.patch("/{team_id}/memos/{memo_id}", response_model=TeamMemoResponse, summary="Update team memo")
async def update_memo(request: Request, team_id: str, memo_id: str, payload: TeamMemoCreate):
    user_id = require_user(request)
    result = await team_service.update_memo(
        team_id, memo_id, user_id,
        content=payload.content,
        tags=payload.tags,
    )
    if not result:
        raise HTTPException(status_code=403, detail="Not found or not authorized")
    return result


@router.post("/{team_id}/memos/{memo_id}/pin", response_model=TeamMemoResponse, summary="Pin/unpin team memo")
async def pin_memo(request: Request, team_id: str, memo_id: str):
    user_id = require_user(request)
    result = await team_service.pin_memo(team_id, memo_id, user_id)
    if not result:
        raise HTTPException(status_code=403, detail="Not found or not authorized")
    return result


@router.delete("/{team_id}/memos/{memo_id}", summary="Delete team memo")
async def delete_memo(request: Request, team_id: str, memo_id: str):
    user_id = require_user(request)
    ok = await team_service.delete_memo(team_id, memo_id, user_id)
    if not ok:
        raise HTTPException(status_code=403, detail="Not found or not authorized")
    return {"status": "deleted"}


# ========================= REVIEW FLOW =========================


@router.post("/{team_id}/memos/{memo_id}/request-review", response_model=TeamMemoResponse, summary="Request review")
async def request_review(request: Request, team_id: str, memo_id: str):
    user_id = require_user(request)
    result = await team_service.request_review(team_id, memo_id, user_id)
    if not result:
        raise HTTPException(status_code=403, detail="Not found or not authorized")
    return result


@router.post("/{team_id}/memos/{memo_id}/review", response_model=TeamMemoResponse, summary="Approve or reject review")
async def submit_review(request: Request, team_id: str, memo_id: str, payload: ReviewAction):
    user_id = require_user(request)
    result = await team_service.submit_review(
        team_id, memo_id, user_id,
        action=payload.action,
        reason=payload.reason,
    )
    if not result:
        raise HTTPException(status_code=403, detail="Not found or not owner")
    return result


# ========================= COMMENTS =========================


@router.post("/{team_id}/memos/{memo_id}/comments", response_model=TeamCommentResponse, summary="Add comment")
async def create_comment(request: Request, team_id: str, memo_id: str, payload: TeamCommentCreate):
    user_id = require_user(request)
    result = await team_service.create_comment(team_id, memo_id, user_id, payload.content)
    if not result:
        raise HTTPException(status_code=403, detail="Not found or not a member")
    return result


@router.get("/{team_id}/memos/{memo_id}/comments", response_model=List[TeamCommentResponse], summary="List comments")
async def list_comments(request: Request, team_id: str, memo_id: str):
    user_id = require_user(request)
    return await team_service.list_comments(team_id, memo_id, user_id)


@router.delete("/{team_id}/comments/{comment_id}", summary="Delete comment")
async def delete_comment(request: Request, team_id: str, comment_id: str):
    user_id = require_user(request)
    ok = await team_service.delete_comment(team_id, comment_id, user_id)
    if not ok:
        raise HTTPException(status_code=403, detail="Not found or not authorized")
    return {"status": "deleted"}


# ========================= REACTIONS =========================


@router.post("/{team_id}/memos/{memo_id}/reactions", summary="Toggle reaction")
async def toggle_reaction(request: Request, team_id: str, memo_id: str, payload: ReactionToggle):
    user_id = require_user(request)
    result = await team_service.toggle_reaction(team_id, memo_id, user_id, payload.emoji)
    if not result:
        raise HTTPException(status_code=400, detail="Invalid emoji or not found")
    return result
