# -*- coding: utf-8 -*-
"""
product_service.py — 产品服务模块（离线模式）

功能：
  - 管理产品列表、产品资料文档
  - 按产品筛选知识库常见问题
  - 提供文档下载路径

用法：
  from services.product_service import get_product_service
  service = get_product_service()
  products = service.get_products()
"""

import json
from pathlib import Path
from typing import Optional

from utils.paths import SCRIPT_DIR, PROJECT_ROOT
from utils.logger import get_logger

logger = get_logger(__name__)

# 产品配置文件路径
PRODUCTS_FILE = SCRIPT_DIR / "products.json"
# 维护手册目录
DOCS_DIR = PROJECT_ROOT / "Docs" / "维护手册"


class ProductService:
    """产品服务：管理产品列表、资料、常见问题"""

    def __init__(self):
        self._products = []
        self._load_products()

    def _load_products(self):
        """加载产品配置"""
        try:
            if PRODUCTS_FILE.exists():
                with open(PRODUCTS_FILE, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self._products = data.get('products', [])
                logger.info(f"[ProductService] 加载 {len(self._products)} 个产品配置")
            else:
                self._products = []
                logger.warning(f"[ProductService] 产品配置文件不存在: {PRODUCTS_FILE}")
        except Exception as e:
            logger.error(f"[ProductService] 加载产品配置失败: {e}")
            self._products = []

    def get_products(self) -> list[dict]:
        """获取所有产品列表（含常见问题数量）"""
        products = []
        for p in self._products:
            product = dict(p)
            # 查询该产品的知识库记录数量
            product['faq_count'] = self._count_faqs(product)
            products.append(product)
        return products

    def get_product(self, product_id: str) -> Optional[dict]:
        """获取单个产品详情"""
        for p in self._products:
            if p['id'] == product_id:
                product = dict(p)
                product['faq_count'] = self._count_faqs(product)
                return product
        return None

    def get_documents(self, product_id: str) -> list[dict]:
        """获取产品的资料文档列表"""
        product = self.get_product(product_id)
        if product:
            return product.get('documents', [])
        return []

    def get_document_path(self, doc_id: str) -> Optional[Path]:
        """获取文档文件路径"""
        for p in self._products:
            for doc in p.get('documents', []):
                if doc['id'] == doc_id:
                    filename = doc.get('filename', '')
                    if not filename:
                        continue
                    # 查找文件：优先在维护手册目录
                    file_path = DOCS_DIR / filename
                    if file_path.exists():
                        return file_path
                    # 备用：在项目根目录下查找
                    alt_path = PROJECT_ROOT / filename
                    if alt_path.exists():
                        return alt_path
        return None

    def get_faqs(self, product_id: str, limit: int = 50) -> list[dict]:
        """获取产品的常见问题列表"""
        product = self.get_product(product_id)
        if not product:
            return []

        # 从知识库搜索该产品的记录
        apk_product = product.get('apk_product', '')
        tags = product.get('tags', [])

        if not apk_product and not tags:
            return []

        try:
            import container
            engine = container.get_search_engine()
            if not engine:
                return []

            records = engine.search_by_product(
                apk_product=apk_product,
                tags=tags,
                limit=limit
            )

            # 转换为 FAQ 格式
            faqs = []
            for r in records:
                faqs.append({
                    'record_id': str(r.get('id', '')),
                    'title': r.get('title', ''),
                    'phenomenon': r.get('phenomenon', ''),
                    'solution': r.get('solution', ''),
                })
            return faqs
        except Exception as e:
            logger.error(f"[ProductService] 获取常见问题失败: {e}")
            return []

    def _count_faqs(self, product: dict) -> int:
        """计算产品的常见问题数量"""
        apk_product = product.get('apk_product', '')
        tags = product.get('tags', [])

        if not apk_product and not tags:
            return 0

        try:
            import container
            engine = container.get_search_engine()
            if not engine:
                return 0
            records = engine.search_by_product(
                apk_product=apk_product,
                tags=tags,
                limit=1000
            )
            return len(records)
        except Exception as e:
            logger.error(f"[ProductService] 计算常见问题数量失败: {e}")
            return 0


# 单例
_product_service = None


def get_product_service() -> ProductService:
    """获取产品服务单例"""
    global _product_service
    if _product_service is None:
        _product_service = ProductService()
    return _product_service
