"""启动确认窗兜底样本落库:单条 insert(都上报、不去重,by design)。"""
from __future__ import annotations

import logging
from datetime import datetime
from typing import Optional

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models.launch_confirm_sample import LaunchConfirmSample
from app.schemas.launch_confirm_sample import LaunchConfirmSampleIn

logger = logging.getLogger("shagua.launch_confirm")


def _trunc(s: Optional[str], n: int) -> Optional[str]:
    """截断到列长上限(PG varchar 超长会报错;繁体长标题等需要)。空 → None。"""
    return s[:n] if s else None


def insert_sample(db: Session, payload: LaunchConfirmSampleIn) -> int:
    """写入一条样本,返回新行 id。"""
    row = LaunchConfirmSample(
        trace_id=_trunc(payload.trace_id, 64),
        device_id=_trunc(payload.device_id, 64),
        host_package=_trunc(payload.host_package, 128),
        target_app=_trunc(payload.target_app, 128),
        system_locale=_trunc(payload.system_locale, 32),
        exec_success=bool(payload.exec_success),
        dialog_title=_trunc(payload.dialog_title, 256),
        payload=payload.payload,
    )
    db.add(row)
    db.commit()
    db.refresh(row)
    return row.id


def list_samples(
    db: Session,
    *,
    exec_success: Optional[bool] = None,
    host_package: Optional[str] = None,
    since: Optional[datetime] = None,
    limit: int = 1000,
) -> list[LaunchConfirmSample]:
    """按条件查样本(pricebot 的 distill_launch_confirm.py 沉淀工具读)。created_at 升序。

    过滤项都可空:exec_success(只看放行成功的)/ host_package(只看某宿主包)/
    since(>= created_at)。limit 兜底防一次拉爆全表。
    """
    stmt = select(LaunchConfirmSample)
    if exec_success is not None:
        stmt = stmt.where(LaunchConfirmSample.exec_success == exec_success)
    if host_package:
        stmt = stmt.where(LaunchConfirmSample.host_package == host_package)
    if since is not None:
        stmt = stmt.where(LaunchConfirmSample.created_at >= since)
    stmt = stmt.order_by(LaunchConfirmSample.created_at.asc()).limit(limit)
    return list(db.execute(stmt).scalars().all())
