#!/usr/bin/env python3
"""Extrai rotas, endpoints e simbolos de sessao das DLLs do dump.

    python routes_extract.py
    python routes_extract.py --root extracted_dump/dump/NvPlugins

Le as DLLs locais (ASCII + UTF-16LE), filtra por padroes de rota/protocolo
e grava routes_report.txt + routes_report.json.
"""
import argparse
import json
import re
import sys
from collections import defaultdict
from pathlib import Path

ROOT = Path(r"C:\Users\Admin\Links\historia-index\extracted_dump\dump\NvPlugins")
OUT = Path(r"C:\Users\Admin\Links\historia-index\routes_report")

PATTERNS = {
    "uri": re.compile(r"(?:rtsp|https?|ws|tcp|udp)://[A-Za-z0-9_.:/{}\[\]$%+-]{3,}"),
    "path": re.compile(r"(/(?:v\d|v\.\d)[\w./{}.-]{2,})|(/(?:AppInfo|EventAPI|NvCamera|SDK|Session|Stream)[\w./{}.-]*)"),
    "loopback": re.compile(r"\b(?:127\.\d+\.\d+\.\d+|localhost)(?::\d{2,5})?"),
    "port": re.compile(r"\b(?:50101|50103|48010|48005|47998|47999|48000|48001|48002|47995|2020)\b"),
    "session": re.compile(r"\b(?:SetupSession|ResumeSession|PauseSession|StopSession|SessionModify|SessionTimeout|ServerTimerEvent|timerEvent|SessionIdentifier|SessionResultCode|GsgTokenRefresh|PlaytestConfig)\b"),
    "status": re.compile(r"STATUSCODE_[A-Z0-9_]+"),
    "disconnect": re.compile(r"CLIENT_DISCONNECT_[A-Z_]+|CLIENT_RECONNECT_[A-Z_]+"),
    "pipe": re.compile(r"\\\\\.\\pipe\\[A-Za-z0-9_\\.-]+"),
    "bus": re.compile(r"\b(?:Serenity|NvMessageBus[A-Za-z]*|gfn-cc[a-z]*|StreamServerExtendedCommands)\b"),
    "token": re.compile(r"\b(?:GsgTokenRefresh|accessToken|AESKey|TokenRefresh|authToken)\b"),
}

MIN_LEN = 6


def strings_of(blob: bytes):
    out = set()
    for m in re.finditer(rb"[\x20-\x7e]{%d,}" % MIN_LEN, blob):
        out.add(m.group().decode("latin-1"))
    for m in re.finditer(rb"(?:[\x20-\x7e]\x00){%d,}" % MIN_LEN, blob):
        out.add(m.group().decode("utf-16le", "replace"))
    return out


def main():
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    except AttributeError:
        pass
    ap = argparse.ArgumentParser()
    ap.add_argument("--root", default=str(ROOT))
    args = ap.parse_args()

    root = Path(args.root)
    if not root.exists():
        sys.exit(f"raiz ausente: {root}")

    found = defaultdict(lambda: defaultdict(set))
    files = sorted(root.rglob("*.dll"))
    print(f"{len(files)} DLLs em {root}\n")

    for path in files:
        blob = path.read_bytes()
        strings = strings_of(blob)
        for bucket, rx in PATTERNS.items():
            for s in strings:
                for m in rx.finditer(s):
                    value = m.group().strip()
                    if MIN_LEN <= len(value) <= 220:
                        found[bucket][value].add(path.name)

    lines = []
    total = 0
    for bucket in PATTERNS:
        entries = found[bucket]
        if not entries:
            continue
        lines.append(f"\n## {bucket} ({len(entries)})")
        print(f"## {bucket} ({len(entries)})")
        for value in sorted(entries):
            owners = sorted(entries[value])
            lines.append(f"  {value}")
            lines.append(f"      {', '.join(owners)}")
            total += 1
            if len(owners) <= 4:
                print(f"  {value}")
                print(f"      {', '.join(owners)}")

    OUT.with_suffix(".txt").write_text("\n".join(lines), encoding="utf-8")
    OUT.with_suffix(".json").write_text(
        json.dumps({b: {k: sorted(v) for k, v in d.items()} for b, d in found.items()},
                   ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"\n{total} valores unicos -> {OUT}.txt / {OUT}.json")


if __name__ == "__main__":
    main()
