import csv
import sys

def csv_to_markdown_table(csv_file):
    """Convert a CSV file to a Markdown table string."""
    with open(csv_file, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        rows = list(reader)

    if not rows:
        return ""

    # Create markdown table
    md_table = []

    # Header row
    header = rows[0]
    md_table.append("| " + " | ".join(header) + " |")

    # Separator row
    separator = ["---"] * len(header)
    md_table.append("| " + " | ".join(separator) + " |")

    # Data rows
    for row in rows[1:]:
        md_table.append("| " + " | ".join(row) + " |")

    return "\n".join(md_table)

def main():
    if len(sys.argv) != 2:
        print("Usage: python csv_to_md.py <input_file.csv>")
        sys.exit(1)

    input_file = sys.argv[1]

    try:
        # Convert CSV to markdown table
        markdown_table = csv_to_markdown_table(input_file)

        # Generate output filename
        output_file = input_file.replace('.csv', '.md')

        # Write to markdown file
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(markdown_table)

        print(f"✅ {output_file} created successfully")
    except Exception as e:
        print(f"❌ Error: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    main()
