from __future__ import annotations

class TableModel:
    def __init__(self, columns, rows=None):
        self.columns = list(columns)
        self.rows = [list(r) for r in (rows or [])]
        self.filtered_rows = self.rows[:]
        self.page_size = 10
        self.page_index = 0

    def sort_by(self, column, reverse=False):
        idx = self.columns.index(column) if isinstance(column, str) else int(column)
        self.filtered_rows.sort(key=lambda r: str(r[idx]).lower(), reverse=reverse)
        return self.filtered_rows

    def filter(self, query: str):
        q = query.lower().strip()
        if not q:
            self.filtered_rows = self.rows[:]
        else:
            self.filtered_rows = [r for r in self.rows if any(q in str(cell).lower() for cell in r)]
        self.page_index = 0
        return self.filtered_rows

    def set_page_size(self, size: int):
        self.page_size = max(1, int(size))

    def get_page(self, index=None):
        if index is not None:
            self.page_index = max(0, int(index))
        start = self.page_index * self.page_size
        end = start + self.page_size
        return self.filtered_rows[start:end]

    def edit_cell(self, row_index: int, column, value):
        idx = self.columns.index(column) if isinstance(column, str) else int(column)
        self.rows[row_index][idx] = value
        self.filtered_rows = self.rows[:]
        return value

    def append(self, row):
        self.rows.append(list(row))
        self.filtered_rows = self.rows[:]
