from engine.gates import start_file
from features.session_briefing.start import start_block
from engine.stored import write_text

COMPACTED = """THIS WINDOW WAS JUST COMPACTED. The summary kept what was done and dropped what was decided. Before touching anything:
  journal message recent          the latest messages, yours and the user's, in full
  journal conversation --back=1   the stretch the summary replaced
  journal user                    the user's own words, in full
  journal open                    the work still open, with its notes
  journal search <term>           before saying "we decided" or "earlier you said"
Load the journal skill again (Skill: journal); the compaction emptied it. Then carry on with the open work below.

"""


def briefing(call) -> str:
    path = start_file(call.record.root, call.record.env, call.provider.compacted(call.hook))
    if not path.is_file():
        rebuild(call.record)
    return path.read_text() if path.is_file() else ""


def rebuild(record) -> None:
    block = start_block(record)
    for compacted in (False, True):
        path, text = start_file(record.root, record.env, compacted), COMPACTED + block if compacted else block
        if not path.is_file() or path.read_text() != text:
            write_text(path, text)
