
from typing import List, Optional
from fastapi import APIRouter, Body, HTTPException, Request, Query
from common.team.schemas import (
    TeamCreate, TeamUpdate, TeamResponse,
    TeamMemoCreate, TeamMemoResponse, TeamCommentCreate, TeamCommentResponse,
    ReviewAction, ReactionToggle
)
from common.team.services import team_service

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


def require_user(request: Request) -> str:
    user_id = getattr(request.state, "user_id", None)
    import os
    if os.getenv('DISABLE_AUTH', 'false').lower() == 'true':
        return user_id or 'testuser_local'
    if not user_id:
        raise HTTPException(status_code=401, detail="Authentication required")
    return user_id


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

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


@router.get("", response_model=List[TeamResponse])
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)
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")
    return result


@router.put("/{team_id}", response_model=TeamResponse)
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="Forbidden or not found")
    return result


@router.delete("/{team_id}")
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="Only owner can delete")
    return {"ok": True}


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

@router.post("/join")
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.delete("/{team_id}/members/{target_user_id}")
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="Forbidden")
    return {"ok": True}


@router.post("/{team_id}/leave")
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=403, detail="Owner cannot leave — delete team instead")
    return {"ok": True}


# ========================= TEAM MEMOS (DRAFTS) =========================

@router.post("/{team_id}/memos", response_model=TeamMemoResponse)
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, payload.content, payload.tags)
    if not result:
        raise HTTPException(status_code=403, detail="Not a member")
    return result


@router.get("/{team_id}/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")
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.put("/{team_id}/memos/{memo_id}", response_model=TeamMemoResponse)
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="Forbidden or not found")
    return result


@router.delete("/{team_id}/memos/{memo_id}")
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="Forbidden or not found")
    return {"ok": True}


@router.post("/{team_id}/memos/{memo_id}/pin")
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="Forbidden or not found")
    return result


# ========================= DRAFT → MAIN MERGE =========================

@router.post("/{team_id}/memos/{memo_id}/merge")
async def merge_to_main(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="Only owner can merge")
    return result


@router.post("/{team_id}/memos/{memo_id}/unmerge")
async def unmerge_to_draft(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="Only owner can unmerge")
    return result


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

@router.post("/{team_id}/memos/{memo_id}/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="Forbidden or not found")
    return result


@router.post("/{team_id}/memos/{memo_id}/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, payload.action, payload.reason or "")
    if not result:
        raise HTTPException(status_code=403, detail="Only owner can review")
    return result


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

@router.post("/{team_id}/memos/{memo_id}/comments", response_model=TeamCommentResponse)
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="Forbidden or not found")
    return result


@router.get("/{team_id}/memos/{memo_id}/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}")
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="Forbidden or not found")
    return {"ok": True}


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

@router.post("/{team_id}/memos/{memo_id}/react")
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=403, detail="Forbidden or invalid emoji")
    return result
