import os
import re
import subprocess
from datetime import datetime

def get_git_creation_date(file_path, line_number):
    try:
        # Use git blame to find the timestamp of the line
        cmd = ["git", "blame", "-L", f"{line_number},{line_number}", "--porcelain", file_path]
        result = subprocess.run(cmd, capture_output=True, text=True)
        if result.returncode == 0:
            for line in result.stdout.split('\n'):
                if line.startswith('author-time '):
                    timestamp = int(line.split(' ')[1])
                    return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d")
    except Exception as e:
        pass
    return None

def repair_file(file_path):
    print(f"Repairing {file_path}...")
    with open(file_path, 'r') as f:
        lines = f.readlines()

    new_lines = []
    modified = False
    
    i = 0
    while i < len(lines):
        line = lines[i]
        new_lines.append(line)
        
        # Look for headline
        if line.startswith('*'):
            # Find the PROPERTIES drawer
            j = i + 1
            has_properties = False
            has_created = False
            properties_line_idx = -1
            
            # Check up to 10 lines ahead for performance
            while j < len(lines) and j < i + 10 and not lines[j].startswith('*'):
                if ":PROPERTIES:" in lines[j]:
                    has_properties = True
                    properties_line_idx = j
                if ":CREATED:" in lines[j]:
                    has_created = True
                    break
                if ":END:" in lines[j]:
                    break
                j += 1
            
            if has_properties and not has_created:
                # Use git blame on the headline line
                creation_date = get_git_creation_date(file_path, i + 1)
                
                if creation_date:
                    dt = datetime.strptime(creation_date, "%Y-%m-%d")
                    org_date = dt.strftime("[%Y-%m-%d %a]")
                    
                    # Advance and append original lines until :PROPERTIES:
                    while i < properties_line_idx:
                        i += 1
                        new_lines.append(lines[i])
                    
                    new_lines.append(f":CREATED:  {org_date}\n")
                    modified = True
        i += 1

    if modified:
        with open(file_path, 'w') as f:
            f.writelines(new_lines)
        print(f"DONE: Repaired {file_path}")
    else:
        print(f"SKIP: No changes needed for {file_path}")

if __name__ == "__main__":
    # Test on a small portion first if needed, but here we go
    files = ["inbox-atoms.org", "inbox-emacs.org", "inbox-posts.org"]
    for f in files:
        if os.path.exists(f):
            repair_file(f)
