# utils.py

import os
import csv
from fpdf import FPDF

def ensure_outputs_folder():
    os.makedirs("outputs", exist_ok=True)

def save_txt(content, path="outputs/last_result.txt"):
    with open(path, "w") as f:
        f.write(content)


def export_pdf(content, path="outputs/last_report.pdf"):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=12)

    # Replace common problematic characters
    content = (
        content.replace("’", "'")
               .replace("“", '"')
               .replace("”", '"')
               .replace("–", "-")
               .replace("—", "-")
    )

    for line in content.split('\n'):
        pdf.multi_cell(0, 10, line)
    pdf.output(path)   

def save_csv_report(content, job_title, company_name, location, salary, source, path="outputs/last_result.csv"):

    lines = content.splitlines()
    verdict = next((line.split(":")[1].strip() for line in lines if line.startswith("Verdict:")), "N/A")
    confidence = next((line.split(":")[1].strip() for line in lines if line.startswith("Confidence:")), "N/A")
    error = next((line.split(":")[1].strip() for line in lines if line.startswith("Margin of error:")), "N/A")

    with open(path, mode="w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["Title", "Company", "Location", "Salary", "Source", "Verdict", "Confidence", "Error"])
        writer.writerow([job_title, company_name, location, salary, source, verdict, confidence, error])
