import csv
import sys

input_file = sys.argv[1]
output_file = sys.argv[2]
new_file = "merged.csv"

# Build dictionary mapping comment -> author from input file
comment_to_author = {}
with open(input_file, "r", encoding="utf-8") as f_in:
    reader = csv.DictReader(f_in)
    for row in reader:
        comment = row["comment"].strip()
        author = row["author"].strip()
        comment_to_author[comment] = author

# Read output file, add author, and write to new file
with open(output_file, "r", encoding="utf-8") as f_out, \
     open(new_file, "w", encoding="utf-8", newline="") as f_new:
    
    reader = csv.DictReader(f_out)
    fieldnames = reader.fieldnames
    
    # Insert "author" after "representative"
    insert_pos = fieldnames.index("representative") + 1
    new_fieldnames = fieldnames[:insert_pos] + ["author"] + fieldnames[insert_pos:]
    
    writer = csv.DictWriter(f_new, fieldnames=new_fieldnames)
    writer.writeheader()
    
    for row in reader:
        comment = row["comment"].strip()
        row["author"] = comment_to_author.get(comment, "UNKNOWN")
        writer.writerow(row)

print(f"Merged file created: {new_file}")
