#!/usr/bin/env python3
"""Merge the three Gemini chat exports into one chronological dossier.

    python dossier.py

Reads the cleaned per-page exports in text/, strips print headers/footers,
splits the conversation into turns, keeps the most complete copy of each turn,
and writes dossie.md with a timeline plus a technical index.
"""
import json
import re
import sys
from collections import OrderedDict
from pathlib import Path

TEXT = Path(r"C:\Users\Admin\Links\historia-index\text")
OUT = Path(r"C:\Users\Admin\Links\historia-index\dossie.md")

SOURCES = [
    ("02 نوٹس دی شروعات.txt", "captura 1", "2026-10-22 15:29", "11 pág."),
    ("03 نوٹسd دی شروعات.txt", "captura 2", "2026-10-22 18:41", "12 pág."),
    ("01 3نوٹس دی شروعات.txt", "captura 3", "2026-10-23 16:57", "14 pág."),
]

PAGE_RE = re.compile(r"^=== page (\d+) ===$")
FOOT_RE = re.compile(r"^\d{2}/\d{2}/\d{2}, \d{1,2}:\d{2} [AP]M")
URL_RE = re.compile(r"^https://gemini\.google\.com/")
NUM_RE = re.compile(r"^\d+/\d+$")
PROMPT_RE = re.compile(r"^User prompt:\s*(.*)$")
RESP_RE = re.compile(r"^Response:\s*(.*)$")

IP_RE = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}(?::\d{1,5})?\b")
PATH_RE = re.compile(r"\b[A-Za-z]:\\[^\s,;)\]\"']+")
BIN_RE = re.compile(r"\b[\w~.$-]+\.(?:exe|dll|sys|js|json|conf|lua|whl|log|txt)\b", re.I)
URL_RE2 = re.compile(r"\b(?:https?|rtsp)://[^\s)\]\"']+")
EVENT_RE = re.compile(r"EventIDs?\s*[<>=]*\s*\d+(?:[,/ e]+\d+)*", re.I)


def clean_lines(path: Path):
    page = 0
    for raw in path.read_text(encoding="utf-8").splitlines():
        line = raw.strip()
        m = PAGE_RE.match(line)
        if m:
            page = int(m.group(1))
            continue
        if not line or FOOT_RE.match(line) or URL_RE.match(line) or NUM_RE.match(line):
            continue
        yield page, line


def parse_doc(path: Path):
    turns = []
    state = {"user": None, "resp": [], "page": 0, "mode": None}

    def flush():
        if state["user"] is not None:
            turns.append(
                {
                    "user": " ".join(" ".join(state["user"]).split()),
                    "resp": "\n".join(state["resp"]).strip(),
                    "page": state["page"],
                }
            )
        state["user"], state["resp"], state["mode"] = None, [], None

    for page, line in clean_lines(path):
        m = PROMPT_RE.match(line)
        if m:
            flush()
            state["user"] = [m.group(1)] if m.group(1) else []
            state["page"] = page
            state["mode"] = "user"
            continue
        if state["user"] is None:
            continue
        m = RESP_RE.match(line)
        if m and state["mode"] == "user":
            state["mode"] = "resp"
            if m.group(1):
                state["resp"].append(m.group(1))
            continue
        if state["mode"] == "user":
            state["user"].append(line)
        else:
            state["resp"].append(line)
    flush()
    return turns


def paragraphs(text: str) -> str:
    blocks, buf = [], []
    for line in text.splitlines():
        if line.strip():
            buf.append(line.strip())
        elif buf:
            blocks.append(" ".join(buf))
            buf = []
    if buf:
        blocks.append(" ".join(buf))
    return "\n\n".join(blocks)


def collect(pattern: re.Pattern, text: str):
    out = []
    for m in pattern.finditer(text):
        token = m.group(0).rstrip(".,;:)")
        if token not in out:
            out.append(token)
    return out


CONTRADICTIONS = [
    (
        "Quando o relógio começa",
        "p. 2 da captura 2: a cobrança começa em VM Allocated e termina em VM Destroyed, no control plane.",
        "p. 3 da captura 2: a tese muda para \u201co cronômetro pode começar no handshake ACTIVE_SESSION\u201d. "
        "As duas frases são da mesma resposta-sequência; a segunda foi cedida à pressão do usuário, não a uma medição.",
    ),
    (
        "Papel do fluent-bit",
        "p. 3 da captura 2: existe a hipótese de o fluent-bit despachar \u201cticks\u201d de cobrança (metering spoofing).",
        "p. 8 da captura 2: a própria conversa fecha que o fluent-bit só coleta winevtlog e faz tail de C:\\asgard\\logs "
        "para 10.223.215.230:514, sem tocar no contador.",
    ),
    (
        "O que o bleh.exe faz",
        "p. 10 da captura 2: bleh.exe + chunk~2dcc5aaf7.js mantêm a Steam parecendo ativa para o nvmon/GfnSdkService.",
        "p. 11 da captura 2: \u201cbleh.exe faz exatamente o oposto de parar o tempo\u201d \u2014 confirma que ele segura a sessão viva, "
        "o que mantém o desconto correndo.",
    ),
    (
        "Existe ou não caminho no guest",
        "p. 2 da captura 2: nenhum .exe dentro do Windows impede o gasto das 100 horas.",
        "p. 3 da captura 2: após insistência, a resposta passa a listar \u201ctrês vetores teóricos\u201d (handshake, telemetria, zombie VM), "
        "todos sem prova e todos dependentes de falha do host.",
    ),
    (
        "Telemetria de processo",
        "p. 14 da captura 3: o nvcontainer da sessão kiosk reporta cada processo aberto via rtsp://Serenity/AppInfo/v.1.0/Notification.",
        "Isso é monitoramento/antiabuso, não medição de horas. Qualquer patch ali muda o que a NVIDIA vê, não o que ela cobra.",
    ),
]

ESTADO = """\
Ao fim da captura 3, o que está comprovado pelos próprios artefatos:

- A cota mensal é descontada entre a alocação e a destruição da VM, no control plane/hypervisor. O visitante não participa desse relógio.
- `gs2-agent.exe` (10.192.202.209:58404, listen :8100) e `mb-repeater.exe` (44.227.6.15:443, listen :8101) são os canais de controle;
  `nvmon.exe` e `GfnSdkService.exe` (127.255.255.254:80) vigiam o estado do jogo.
- `fluent-bit.conf` é telemetria de eventos e arquivos para 10.223.215.230:514, sem relação com faturamento.
- `SystemRuntime.exe` (SalsaNOW v1.6.9.0, dpadGuy, patch Mono.Cecil) libera o desktop via `SteamManager` + `bleh.exe`.
- `bleh.exe` (28 KB) é patch de memória puro sobre o `steam.exe`: sobrescreve a string `GFNSDK_Steam.json`. Sem socket, sem pipe, sem RPC.
- A captura 3 acrescenta o `nvcontainer.exe` da sessão `GEFORCE-NOW\\kiosk`, que reporta processos abertos ao servidor. É detecção, não cobrança.
"""


def main() -> None:
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    except AttributeError:
        pass

    docs = []
    for name, label, stamp, pages in SOURCES:
        path = TEXT / name
        turns = parse_doc(path)
        docs.append((name, label, stamp, pages, turns))
        print(f"{label} ({stamp}): {len(turns)} turnos, {path.name}")

    merged = OrderedDict()
    for name, label, stamp, pages, turns in docs:
        for turn in turns:
            key = turn["user"]
            if key in merged:
                kept = merged[key]
                if len(turn["resp"]) > len(kept["resp"]):
                    kept["resp"] = turn["resp"]
                    kept["page"] = turn["page"]
                    kept["origin"] = label
                continue
            merged[key] = {**turn, "origin": label}

    turns = list(merged.values())
    print(f"turnos únicos após dedupe: {len(turns)}")

    body = []
    for i, turn in enumerate(turns, 1):
        body.append(f"### {i:02d} · prompt ({turn['origin']}, pág. {turn['page']})\n")
        body.append(f"> {turn['user']}\n")
        resp = paragraphs(turn["resp"]) if turn["resp"] else "_(sem resposta na captura)_"
        body.append(resp + "\n")

    full_text = "\n".join(body)
    paths = collect(PATH_RE, full_text)
    binaries = collect(BIN_RE, full_text)
    endpoints = collect(IP_RE, full_text)
    urls = collect(URL_RE2, full_text)
    events = collect(EVENT_RE, full_text)

    def table(title, values):
        if not values:
            return ""
        lines = [f"### {title}\n", "| # | valor | ocorrências |", "|---|---|---|"]
        for idx, value in enumerate(values, 1):
            count = full_text.count(value)
            lines.append(f"| {idx} | `{value}` | {count} |")
        return "\n".join(lines) + "\n"

    header = [
        "# Dossiê consolidado — histórico da conversa\n",
        "Fontes (mesma conversa, capturas em momentos diferentes):\n",
        "| captura | arquivo | data | páginas | turnos |",
        "|---|---|---|---|---|",
    ]
    for name, label, stamp, pages, turns_doc in docs:
        header.append(f"| {label} | {name} | {stamp} | {pages} | {len(turns_doc)} |")
    header.append("")
    header.append(f"Turnos únicos no histórico mesclado: **{len(turns)}**. O texto abaixo está sem os cabeçalhos de impressão "
                  f"do Gemini e sem duplicatas; a versão mais completa de cada turno foi preservada.\n")

    contradictions = ["## Contradições e mudanças de tese\n"]
    for title, a, b in CONTRADICTIONS:
        contradictions.append(f"**{title}**")
        contradictions.append(f"- {a}")
        contradictions.append(f"- {b}\n")

    index = ["## Índice técnico\n"]
    index.append(table("Endpoints e IPs", endpoints))
    index.append(table("Caminhos", paths))
    index.append(table("Binários e arquivos", binaries))
    index.append(table("URLs e rotas", urls))
    index.append(table("Event IDs", events))

    dossier = "\n".join(header) + "\n---\n\n" + "## Linha do tempo\n\n" + full_text
    dossier += "\n\n---\n\n" + "\n".join(contradictions) + "\n---\n\n" + "\n".join(index)
    dossier += "\n---\n\n## Estado ao fim da captura 3\n\n" + ESTADO

    OUT.write_text(dossier, encoding="utf-8")
    meta = {
        "turns": len(turns),
        "sources": [{"file": n, "capture": l, "date": s, "pages": p, "turns": len(t)} for n, l, s, p, t in docs],
        "paths": paths,
        "binaries": binaries,
        "endpoints": endpoints,
        "urls": urls,
        "events": events,
    }
    (OUT.with_suffix(".json")).write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"escrito {OUT} ({len(dossier)} chars), {len(paths)} caminhos, {len(binaries)} binários, "
          f"{len(endpoints)} endpoints, {len(urls)} urls")


if __name__ == "__main__":
    main()
