"""Worker / dream 触发的技能自学自动跑批。"""

from __future__ import annotations

from pathlib import Path
from typing import Any

from niannian.soul.cultural_learning import CulturalLearningService
from niannian.soul.learning_schedule import local_now, schedule_gate
from niannian.soul.reflect_loop import ReflectLoop
from niannian.soul.search_providers import build_search_provider_from_yaml
from niannian.soul.web_learning import WebLearningService
from niannian.soul.web_learning_runner import WebLearningRunner


def run_skill_learning_tick(
    nn,
    *,
    manual: bool = False,
) -> dict[str, Any]:
    """在时段内且 auto_learning 开启时跑一批 web 技能自学。"""
    cultural = CulturalLearningService(nn._subject_store, nn._config, home=nn._home)
    web_svc = WebLearningService(nn._subject_store, nn._config, home=nn._home)
    state = web_svc.load_state()
    auto = bool(state.get("auto_learning", state.get("auto_web_search")))
    if not auto and not manual:
        return {"ok": True, "ran": False, "reason": "auto_disabled"}

    cfg = web_svc.load_yaml_config()
    sched = cfg.get("schedule") or {}
    tz = str(sched.get("timezone") or "Asia/Shanghai")
    ok_sched, sched_reason = schedule_gate(
        sched,
        manual=manual,
        bootstrap_complete=cultural.is_bootstrap_complete(),
        now=local_now(tz),
    )
    if not ok_sched:
        return {"ok": True, "ran": False, "reason": sched_reason}

    ok, reason = web_svc.can_run_batch(manual=manual)
    if not ok:
        return {"ok": True, "ran": False, "reason": reason}

    yaml_cfg = web_svc.load_yaml_config()
    search = build_search_provider_from_yaml(yaml_cfg)
    loop = ReflectLoop(nn._subject_store, config=nn._config)
    runner = WebLearningRunner(web_svc, reflect_loop=loop, ingest_fn=nn.ingest, config=nn._config)
    result = runner.run_batch(search=search, project=nn.project)
    return {"ok": True, "ran": True, "result": result}
