import sys
import pandas as pd
import numpy as np

def main():
    if len(sys.argv) != 5:
        print("Error: Incorrect number of parameters")
        sys.exit(1)

    input_file = sys.argv[1]
    weights = sys.argv[2].split(',')
    impacts = sys.argv[3].split(',')
    output_file = sys.argv[4]

    try:
        df = pd.read_csv(input_file)
    except:
        print("Error: File not found")
        sys.exit(1)

    if df.shape[1] < 3:
        print("Error: Input file must contain three or more columns")
        sys.exit(1)

    data = df.iloc[:, 1:]

    try:
        data = data.astype(float)
    except:
        print("Error: From 2nd to last columns must contain numeric values only")
        sys.exit(1)

    if len(weights) != data.shape[1] or len(impacts) != data.shape[1]:
        print("Error: Number of weights, impacts and columns must be same")
        sys.exit(1)

    for i in impacts:
        if i not in ['+', '-']:
            print("Error: Impacts must be either + or -")
            sys.exit(1)

    weights = np.array(weights, dtype=float)

    norm = np.sqrt((data ** 2).sum())
    normalized_data = data / norm
    weighted_data = normalized_data * weights

    ideal_best = []
    ideal_worst = []

    for i in range(len(impacts)):
        if impacts[i] == '+':
            ideal_best.append(weighted_data.iloc[:, i].max())
            ideal_worst.append(weighted_data.iloc[:, i].min())
        else:
            ideal_best.append(weighted_data.iloc[:, i].min())
            ideal_worst.append(weighted_data.iloc[:, i].max())

    ideal_best = np.array(ideal_best)
    ideal_worst = np.array(ideal_worst)

    distance_best = np.sqrt(((weighted_data - ideal_best) ** 2).sum(axis=1))
    distance_worst = np.sqrt(((weighted_data - ideal_worst) ** 2).sum(axis=1))

    topsis_score = distance_worst / (distance_best + distance_worst)

    df["Topsis Score"] = topsis_score
    df["Rank"] = topsis_score.rank(ascending=False)

    df.to_csv(output_file, index=False)
    print("Result saved to", output_file)
