# Copyright (c) 2025, JINGROW
# License: MIT. See LICENSE

from __future__ import annotations

from typing import Any, Iterable

import jingrow
from jingrow.model.base_page import BasePage, get_controller


def get_pg(*args, **kwargs):
    """本地版 get_pg：兼容云端签名。

    支持：
    - get_pg("PageType", name)
    - get_pg({"pagetype": "PageType", ...})
    - get_pg(pagetype="PageType", field=...)
    """
    if args:
        if isinstance(args[0], BasePage):
            return args[0]
        elif isinstance(args[0], str):
            pagetype = args[0]
        elif isinstance(args[0], dict):
            kwargs = args[0]
        else:
            raise ValueError("First non keyword argument must be a string or dict")

    if len(args) < 2 and kwargs:
        if "pagetype" in kwargs:
            pagetype = kwargs["pagetype"]
        else:
            raise ValueError('"pagetype" is a required key')

    controller = get_controller(pagetype)
    if controller:
        return controller(*args, **kwargs)

    raise ImportError(pagetype)


class Page(BasePage):
    """最小可用 Page，复用 jingrow 本地数据库 API（save_pg等）
    仅保留 pagetype 生命周期接口：insert/save/delete/run_method。
    """

    def insert(self, **kwargs) -> "Page":
        self.set("__islocal", True)
        self.run_method("before_insert")
        jingrow.save_pg(self)
        self.run_method("after_insert")
        return self

    def save(self, **kwargs) -> "Page":
        self.run_method("before_save")
        jingrow.save_pg(self)
        self.run_method("on_update")
        return self

    def delete(self, **kwargs):
        self.run_method("on_trash")
        return jingrow.delete_pg(self.pagetype, self.name)

    def run_method(self, method: str, *args, **kwargs):
        fn = getattr(self, method, None)
        if callable(fn):
            return fn(*args, **kwargs)
        return None

    # 兼容云端常用辅助
    def as_dict(self) -> dict[str, Any]:
        d = {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
        d["pagetype"] = self.pagetype
        return d

    def get_all_children(self) -> list["Page"]:
        children = []
        for df in self.meta.get_table_fields():
            value = getattr(self, df.fieldname, None)
            if value:
                children.extend(value)
        return children


