#!/usr/bin/env python3
"""
Fix source_verse column in CSV where verse ranges like 4-5 got converted to dates (04-May).
Extracts correct verse from shloka_id.
"""

import csv
import re

def extract_verse_from_shloka_id(shloka_id):
    """Extract verse part from CH_SU_1/4-5 -> '4-5'"""
    match = re.match(r'CH_[A-Z]+_\d+/(.*)', shloka_id)
    if match:
        return match.group(1)
    return ""

def is_corrupted_verse(verse):
    """Check if verse looks like a date: 04-May, 06-Jul, Aug-14, etc."""
    if not verse:
        return False
    # Date patterns: month names, leading zeros with dash
    month_pattern = r'^(\d{2}-)?(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(-\d{2})?$'
    return bool(re.match(month_pattern, verse, re.IGNORECASE))

def fix_csv():
    input_file = "shlokas_export_2026-05-14.csv"
    output_file = "shlokas_export_2026-05-14_FIXED.csv"

    print(f"Fixing {input_file}...")

    with open(input_file, 'r', encoding='utf-8-sig') as f:
        reader = csv.DictReader(f)
        headers = reader.fieldnames
        rows = []
        fixed = 0
        total = 0

        for row in reader:
            total += 1
            shloka_id = row.get('shloka_id', '')
            current_verse = row.get('source_verse', '')

            # Extract correct verse from shloka_id
            correct_verse = extract_verse_from_shloka_id(shloka_id)

            # Check if current verse is corrupted (looks like a date)
            if is_corrupted_verse(current_verse) or current_verse != correct_verse:
                row['source_verse'] = correct_verse
                fixed += 1

            rows.append(row)

    # Write fixed file
    with open(output_file, 'w', encoding='utf-8', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=headers)
        writer.writeheader()
        writer.writerows(rows)

    print(f"Total rows: {total}")
    print(f"Fixed rows: {fixed}")
    print(f"Saved to: {output_file}")

    # Verify
    print("\n--- Verification ---")
    for row in rows[:10]:
        sid = row['shloka_id']
        ch = row['source_chapter']
        vr = row['source_verse']
        print(f"{sid} | chapter={ch} | verse={vr}")

if __name__ == "__main__":
    fix_csv()
