from loguru import logger

from bit_tools import get_browser_lists_Browser, get_group_lists
from models import db1
from models.ips import Ips
from models.xstart import Xstart
from models.xtoken import XToken


def ensure_tables():
    db1.connect(reuse_if_open=True)
    try:
        db1.create_tables([XToken, Xstart, Ips], safe=True)
    finally:
        if not db1.is_closed():
            db1.close()


def sync_xstart_from_bitbrowser(group_name="推特", max_pages=10):
    fz_datas = get_group_lists()
    if group_name not in fz_datas:
        logger.error(f"未找到分组：{group_name}")
        return

    group_id = fz_datas[group_name]
    created = 0
    scanned = 0

    db1.connect(reuse_if_open=True)
    try:
        for page in range(max_pages):
            browser_list = get_browser_lists_Browser(id=group_id, page=page)
            if not browser_list:
                break

            for browser in browser_list:
                scanned += 1
                _, is_created = Xstart.get_or_create(
                    bit_id=browser.get("id"),
                )
                if is_created:
                    created += 1
    finally:
        if not db1.is_closed():
            db1.close()

    logger.info(f"已扫描 {scanned} 个浏览器配置，写入 Xstart {created} 条")
