import csv
from pathlib import Path


BASE_DIR = Path(__file__).resolve().parent


def celsius_to_fahrenheit(celsius):
    return round(celsius * 9 / 5 + 32, 2)


def validate_on_train(train_path=BASE_DIR / "train.csv"):
    correct = 0
    total = 0

    with open(train_path, "r", encoding="utf-8", newline="") as fin:
        reader = csv.DictReader(fin)

        for row in reader:
            celsius = float(row["temperature_c"])
            expected = float(row["temperature_f"])
            predicted = celsius_to_fahrenheit(celsius)

            if f"{predicted:.2f}" == f"{expected:.2f}":
                correct += 1
            total += 1

    score = correct / total * 100 if total else 0
    print(f"Verificare pe train.csv: {correct}/{total} corecte ({score:.2f}%)")
    return score


def build_submission(
    test_path=BASE_DIR / "test.csv",
    output_path=BASE_DIR / "submission.csv"
):
    rows = []

    with open(test_path, "r", encoding="utf-8", newline="") as fin:
        reader = csv.DictReader(fin)

        for row in reader:
            celsius = float(row["temperature_c"])
            fahrenheit = celsius_to_fahrenheit(celsius)
            rows.append({
                "SampleID": row["SampleID"],
                "temperature_f": f"{fahrenheit:.2f}",
            })

    with open(output_path, "w", encoding="utf-8", newline="") as fout:
        writer = csv.DictWriter(fout, fieldnames=["SampleID", "temperature_f"])
        writer.writeheader()
        writer.writerows(rows)

    print(f"Am scris {len(rows)} rânduri în {output_path.name}")


if __name__ == "__main__":
    validate_on_train()
    build_submission()
