# 1. Open the data file.

# 2. Write down the names of all the candidates.

# 3. Add a vote count for each candidate.

# 4. Get the total votes for each candidate.

# 5. Get the total votes cast for the election.



# Add our dependencies.
import csv
import os

# Assign a variable to load a file from a path.
file_to_load = os.path.join("Resources/election_results.csv")

# Assign a variable to save the file to a path.
file_to_save = os.path.join("analysis", "election_analysis.txt")

# Initialize a total vote counter.
total_votes = 0

# Candidate options and candidate votes.
candidate_options = []
candidate_votes = {}

#Counties and the number of votes in each
county_list = []
county_votes = {}
county_percentage = {}
turnout_county = ""
turnout_largest = 0
turnout_percentage = 0

# Track the winning candidate, vote count, and percentage.
winning_candidate = ""
winning_count = 0
winning_percentage = 0

# Open the election results and read the file.
with open(file_to_load) as election_data:
    file_reader = csv.reader(election_data)

# Read the header row.
    headers = next(file_reader)

    # Print each row in the CSV file.
    for row in file_reader:
        # Add to the total vote count.
        total_votes += 1
        # Get the counties votes
        county = row[1]
        # If the county does not match any existing county, add the the county to the list.
        if county not in county_list:
            # Add the candidate name to the candidate list.
            county_list.append(county)
            # And begin tracking that candidate's voter count.
            county_votes[county] = 0
            county_percentage[county] = 0
        # Add a vote to that candidate's count.
        county_votes[county] += 1
        # Get the candidate name from each row.
        candidate_name = row[2]

        # If the candidate does not match any existing candidate, add the
        # the candidate list.
        if candidate_name not in candidate_options:
            # Add the candidate name to the candidate list.
            candidate_options.append(candidate_name)
            # And begin tracking that candidate's voter count.
            candidate_votes[candidate_name] = 0
        # Add a vote to that candidate's count.
        candidate_votes[candidate_name] += 1

# Save the results to our text file.
with open(file_to_save, "w") as txt_file:
    # Print the final vote count to the terminal.
    election_results = (
        f"\nElection Results\n"
        f"-------------------------\n"
        f"Total Votes: {total_votes:,}\n"
        f"-------------------------\n"
        f"\nCounty Votes:\n")
    print(election_results, end="")
    # Save the final vote count to the text file.
    txt_file.write(election_results)

    # print voter turnout for each county
    for county in county_votes:
        # Retrieve vote count and percentage.
        votes = county_votes[county]
        vote_percentage = float(votes) / float(total_votes) * 100
        county_percentage[county] = vote_percentage
        county_results = (
            f"{county}: {vote_percentage:.1f}% ({votes:,})")
        #  Save the county's results to our text file.
        txt_file.write(county_results)
        txt_file.write("\n")
        print(county_results)
        # Determine the county with the greatest turnout, turnout percentage.
        if (votes > turnout_largest) and (vote_percentage > turnout_percentage):
            turnout_largest = votes
            turnout_county = county
            turnout_percentage = vote_percentage

    # format our analysis on the counrty's turnouts
    largest_turnout = (
        f"\n-------------------------\n"
        f"Largest County Turnout: {turnout_county}"
        f"\n-------------------------"
    )
    # print the county that had the largest turnout
    print(largest_turnout)
    # write the county that had the largest turnout
    txt_file.write(largest_turnout)

    for candidate in candidate_votes:
        # Retrieve vote count and percentage.
        votes = candidate_votes[candidate]
        vote_percentage = float(votes) / float(total_votes) * 100
        candidate_results = (
            f"{candidate}: {vote_percentage:.1f}% ({votes:,})")

        # Print each candidate's voter count and percentage to the terminal.
        print(candidate_results)
        # Save the candidate results to our text file.
        txt_file.write('\n')
        txt_file.write(candidate_results)
        # Determine winning vote count, winning percentage, and winning candidate.
        if (votes > winning_count) and (vote_percentage > winning_percentage):
            winning_count = votes
            winning_candidate = candidate
            winning_percentage = vote_percentage

    # Print the winning candidate's results to the terminal.
    winning_candidate_summary = (
        f"-------------------------\n"
        f"Winner: {winning_candidate}\n"
        f"Winning Vote Count: {winning_count:,}\n"
        f"Winning Percentage: {winning_percentage:.1f}%\n"
        f"-------------------------\n")
    print(winning_candidate_summary)
    # Save the winning candidate's results to the text file.
    txt_file.write('\n')
    txt_file.write(winning_candidate_summary)
    