"""Firestore 저장 모듈"""

import logging
from typing import Any, Optional

import firebase_admin
from firebase_admin import firestore  # type: ignore[attr-defined]
from firebase_admin import credentials
from google.cloud.firestore import Client as FirestoreClient

from . import config

logger = logging.getLogger(__name__)

_app: Optional[firebase_admin.App] = None

# SERVER_TIMESTAMP sentinel from firebase_admin.firestore
_SERVER_TIMESTAMP = firestore.SERVER_TIMESTAMP  # type: ignore[attr-defined]


def _get_db() -> FirestoreClient:
    """Firestore 클라이언트 싱글톤"""
    global _app
    if _app is None:
        cred = credentials.Certificate(config.FIREBASE_SERVICE_ACCOUNT_KEY)
        _app = firebase_admin.initialize_app(
            cred, {"projectId": config.FIREBASE_PROJECT_ID}
        )
    return firestore.client()  # type: ignore[no-any-return]


def get_active_channels(
    db: Optional[FirestoreClient] = None,
) -> list[dict[str, Any]]:
    """활성 YouTube 채널 목록 조회"""
    if db is None:
        db = _get_db()
    docs = db.collection("youtube_channels").where("isActive", "==", True).stream()
    channels = []
    for doc in docs:
        data = doc.to_dict()
        if data is None:
            continue
        data["doc_id"] = doc.id
        channels.append(data)
    return channels


def is_video_processed(video_id: str, db: Optional[FirestoreClient] = None) -> bool:
    """이미 처리된 영상인지 확인"""
    if db is None:
        db = _get_db()
    docs = (
        db.collection("youtube_knowledge")
        .where("videoId", "==", video_id)
        .limit(1)
        .stream()
    )
    return any(True for _ in docs)


def save_youtube_knowledge(
    data: dict[str, Any],
    db: Optional[FirestoreClient] = None,
) -> str:
    """youtube_knowledge 컬렉션에 메타데이터 저장"""
    if db is None:
        db = _get_db()
    doc_ref = db.collection("youtube_knowledge").document()
    doc_ref.set(
        {
            **data,
            "createdAt": _SERVER_TIMESTAMP,
        }
    )
    logger.info("youtube_knowledge 저장: %s", data.get("videoId"))
    return doc_ref.id


def save_insurance_chunk(
    video_id: str,
    channel_name: str,
    title: str,
    summary: str,
    embedding: list[float],
    video_date: str,
    drive_url: str,
    db: Optional[FirestoreClient] = None,
) -> str:
    """insurance_chunks에 YouTube 요약 저장 (sourceType: 'youtube')"""
    if db is None:
        db = _get_db()
    doc_ref = db.collection("insurance_chunks").document()
    doc_ref.set(
        {
            "companyId": "",
            "companyName": channel_name,
            "productId": video_id,
            "productName": title,
            "pageNumber": 0,
            "chunkText": summary[:2000],
            "embedding": embedding,
            "coverageNames": [],
            "sourceType": "youtube",
            "effectiveDate": video_date,
            "driveFileId": drive_url,
            "createdAt": _SERVER_TIMESTAMP,
        }
    )
    logger.info("insurance_chunks 저장: %s", video_id)
    return doc_ref.id


def update_last_crawled(
    channel_doc_id: str, db: Optional[FirestoreClient] = None
) -> None:
    """채널의 lastCrawledAt 갱신"""
    if db is None:
        db = _get_db()
    db.collection("youtube_channels").document(channel_doc_id).update(
        {
            "lastCrawledAt": _SERVER_TIMESTAMP,
        }
    )
    logger.info("lastCrawledAt 갱신: %s", channel_doc_id)
