# Copyright (c) 2025, JINGROW and contributors
# For license information, please see license.txt

"""
Jingrow Local 数据库查询
与 SaaS 版完全一致的 DatabaseQuery 实现
"""

from typing import Dict, List, Any, Optional, Union

class DatabaseQuery:
    """数据库查询类 - 与 SaaS 版完全一致"""
    
    def __init__(self, doctype: str):
        self.doctype = doctype
        self.filters = {}
        self.fields = []
        self.order_by = None
        self.limit_start = 0
        self.limit_page_length = 20
    
    def where(self, **filters):
        """添加查询条件"""
        self.filters.update(filters)
        return self
    
    def select(self, *fields):
        """选择字段"""
        self.fields = list(fields)
        return self
    
    def order_by(self, field: str, order: str = "asc"):
        """排序"""
        self.order_by = f"{field} {order}"
        return self
    
    def limit(self, start: int = 0, page_length: int = 20):
        """限制结果"""
        self.limit_start = start
        self.limit_page_length = page_length
        return self
    
    def execute(self):
        """执行查询"""
        import jingrow
        return jingrow.get_list(
            self.doctype,
            filters=self.filters,
            fields=self.fields,
            order_by=self.order_by,
            limit_start=self.limit_start,
            limit_page_length=self.limit_page_length
        )
    
    def first(self):
        """获取第一条记录"""
        results = self.limit(0, 1).execute()
        return results[0] if results else None
    
    def count(self):
        """获取记录数量"""
        import jingrow
        return jingrow.db.get_value(
            self.doctype,
            filters=self.filters,
            fieldname="count(*)"
        )
