import os
import json
import re

brain_dir = r"C:\Users\Abhiram P M\.gemini\antigravity-ide\brain"
os.makedirs("recovered_html_all", exist_ok=True)

# Find all transcripts
transcripts = []
for d in os.listdir(brain_dir):
    log_path = os.path.join(brain_dir, d, ".system_generated", "logs", "transcript_full.jsonl")
    if os.path.exists(log_path):
        transcripts.append((os.path.getctime(log_path), log_path))

transcripts.sort(key=lambda x: x[0])

for _, log_path in transcripts:
    with open(log_path, "r", encoding="utf-8") as f:
        for i, line in enumerate(f):
            try:
                step = json.loads(line)
                
                if step.get("type") == "TOOL_RESPONSE":
                    content = step.get("content", "")
                    
                    if "The following code has been modified to include a line number" in content:
                        m = re.search(r"File Path: `file:///(.*?)`", content)
                        if m:
                            filepath = m.group(1).replace("%20", " ")
                            if "Franciscan Society" in filepath and filepath.endswith(".html"):
                                filename = os.path.basename(filepath)
                                
                                lines = content.split("\n")
                                clean_lines = []
                                in_code = False
                                for l in lines:
                                    if l.startswith("The following code has been modified"):
                                        in_code = True
                                        continue
                                    
                                    if in_code:
                                        match = re.match(r"^\d+:\s?(.*)", l)
                                        if match:
                                            clean_lines.append(match.group(1))
                                        else:
                                            clean_lines.append(l)
                                            
                                full_html = "\n".join(clean_lines)
                                
                                # Only overwrite if it's not a tiny fragment
                                if len(full_html) > 1000:
                                    with open(os.path.join("recovered_html_all", filename), "w", encoding="utf-8") as out:
                                        out.write(full_html)
                                    print(f"Recovered {filename} ({len(full_html)} bytes) from {os.path.basename(os.path.dirname(os.path.dirname(os.path.dirname(log_path))))}")
            except Exception as e:
                pass
