import base64
import hashlib
import hmac
import time

from django.conf import settings
from django.shortcuts import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response

from apps.api.serializers import LineSerializer, PostSerializer, UserSerializer
from apps.billboard.models import Line, Post
from apps.lyric.models import User


class PostDetailAPI(APIView):
    def get(self, request, post_id):
        post = get_object_or_404(Post, id=post_id)
        serializer = PostSerializer(post)
        return Response(serializer.data)

class PostLinesAPI(APIView):
    def post(self, request, post_id):
        post = get_object_or_404(Post, id=post_id)
        serializer = LineSerializer(data=request.data, context={"post": post})
        if serializer.is_valid():
            serializer.save(post=post, author=request.user)
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)

class PostsAPI(APIView):
    def get(self, request):
        posts = Post.objects.filter(owner=request.user)
        serializer = PostSerializer(posts, many=True)
        return Response(serializer.data)

    def post(self, request):
        text = request.data.get("text", "")
        post = Post.objects.create(owner=request.user, title=text[:35])
        Line.objects.create(text=text, post=post, author=request.user)
        serializer = PostSerializer(post)
        return Response(serializer.data, status=201)

class UserSearchAPI(APIView):
    def get(self, request):
        q = request.query_params.get("q", "")
        users = User.objects.filter(
            username__icontains=q,
            searchable=True,
        )
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)


class VoiceTURNCredentialsAPI(APIView):
    """Time-limited TURN/STUN credentials for the WebRTC mesh voice client
    (Phase C of [[my-sea-invite-voice-blueprint]]). Implements the coturn
    `use-auth-secret` REST scheme: username = `<expiry>:<user_id>`, credential
    = base64(HMAC-SHA1(username, COTURN_SHARED_SECRET)) — the coturn droplet
    validates it with the same shared secret, so no per-user state is stored
    on either side. Authenticated-only."""

    permission_classes = [IsAuthenticated]

    def get(self, request):
        host = settings.COTURN_TURN_HOST
        ttl = settings.COTURN_TTL
        expiry = int(time.time()) + ttl
        username = f"{expiry}:{request.user.id}"
        digest = hmac.new(
            settings.COTURN_SHARED_SECRET.encode(),
            username.encode(),
            hashlib.sha1,
        ).digest()
        credential = base64.b64encode(digest).decode()

        ice_servers = []
        if host:
            ice_servers.append({"urls": [f"stun:{host}:3478"]})
            ice_servers.append({
                "urls": [
                    f"turn:{host}:3478?transport=udp",
                    f"turn:{host}:3478?transport=tcp",
                ],
                "username": username,
                "credential": credential,
            })
        return Response({
            "iceServers": ice_servers,
            "username": username,
            "credential": credential,
            "ttl": ttl,
        })
