class CC:
    codes = [
        '''
IAM Role
        ''',
        '''
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 5, 4, 5])

model = LinearRegression()
model.fit(X, y)

y_pred = model.predict(X)

plt.scatter(X, y, color='blue', label='Actual Data')
plt.plot(X, y_pred, color='red', linewidth=2, label='Best Fit Line')
plt.title("Linear Regression Example")
plt.xlabel("X (Independent Variable)")
plt.ylabel("Y (Dependent Variable)")
plt.legend()
plt.grid(True)
plt.show()
        ''',
        '''
import sagemaker
from sagemaker import get_execution_role
from sagemaker.inputs import TrainingInput
import boto3
import numpy as np

sagemaker_session = sagemaker.Session()
role = get_execution_role()
region = boto3.Session().region_name

bucket_name = sagemaker_session.default_bucket() 
prefix = 'linear-regression'

train_uri = f"s3://{bucket_name}/{prefix}/train.csv"
test_uri = f"s3://{bucket_name}/{prefix}/test.csv"

print(f"Using Training Data from: {train_uri}")
print(f"Using Testing Data from:  {test_uri}")

container = sagemaker.image_uris.retrieve(
    "linear-learner", region
)

linear_estimator = sagemaker.estimator.Estimator(
    container,
    role,
    instance_count=1,
    instance_type='ml.m5.large',
    output_path=f's3://{bucket_name}/output',
    sagemaker_session=sagemaker_session
)

linear_estimator.set_hyperparameters(
    predictor_type='regressor',
    mini_batch_size=4, 
    epochs=10,
    feature_dim=1    
)

linear_estimator.fit({
    'train': TrainingInput(s3_data=train_uri, content_type='text/csv'),
    'test':  TrainingInput(s3_data=test_uri, content_type='text/csv')
})

from sagemaker.serializers import CSVSerializer
from sagemaker.deserializers import JSONDeserializer

linear_predictor = linear_estimator.deploy(
    initial_instance_count=1,
    instance_type='ml.m5.large',
    serializer=CSVSerializer(),      
    deserializer=JSONDeserializer()  
)

test_x = np.array([[10], [25], [50]])

print("\n--- Prediction Results ---")
results = linear_predictor.predict(test_x)

for i, prediction in enumerate(results['predictions']):
    input_val = test_x[i][0]
    score = prediction['score']
    print(f"Input x: {input_val} | Predicted y: {score:.4f}")

# linear_predictor.delete_endpoint()
        ''',
        '''
import sagemaker
import boto3
import pandas as pd
import numpy as np
import io
import os
from sklearn.preprocessing import StandardScaler

sagemaker_session = sagemaker.Session()
role = sagemaker.get_execution_role()
bucket_name = sagemaker_session.default_bucket()

file_key = 'titanic.csv' 

raw_data_uri = f"s3://{bucket_name}/{file_key}"

print(f"Looking for data at: {raw_data_uri}")

try:
    df = pd.read_csv(raw_data_uri)
    print("Success! Data loaded from S3.")
    print("Shape:", df.shape)
except Exception as e:
    print("Error: Could not find the file in S3.")
    print(f"Please check that 'titanic.csv' is in bucket: {bucket_name}")
    print(f"Error details: {e}")
    raise e

print("\nStarting Preprocessing...")

df['Age'] = df['Age'].fillna(df['Age'].median())
df['Embarked'] = df['Embarked'].fillna(df['Embarked'].mode()[0])

if 'Cabin' in df.columns:
    df.drop('Cabin', axis=1, inplace=True)
df.drop(['PassengerId', 'Name', 'Ticket'], axis=1, inplace=True)

df = pd.get_dummies(df, columns=['Sex', 'Embarked'], drop_first=True)

scaler = StandardScaler()
cols_to_scale = ['Age', 'Fare']
df[cols_to_scale] = scaler.fit_transform(df[cols_to_scale])

print("Preprocessing Complete.")
print(df.head())

processed_filename = "titanic_cleaned.csv"
prefix_processed = "titanic-lab/processed"

df.to_csv(processed_filename, index=False)

processed_s3_path = sagemaker_session.upload_data(
    path=processed_filename, 
    bucket=bucket_name, 
    key_prefix=prefix_processed
)

print("\n------------------------------------------------")
print("LAB COMPLETE")
print(f"Cleaned dataset saved to S3 at: {processed_s3_path}")
print("------------------------------------------------")
        ''',
        '''
import sagemaker
import boto3
import pandas as pd
import numpy as np
import os
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sagemaker.tuner import IntegerParameter, ContinuousParameter, HyperparameterTuner
from sagemaker.inputs import TrainingInput

session = sagemaker.Session()
role = sagemaker.get_execution_role()
bucket = session.default_bucket()
prefix = 'lab-hpo-xgboost'
region = boto3.Session().region_name

print(f"Region: {region}")
print(f"Bucket: {bucket}")

print("\nGenerating synthetic data...")

X, y = make_classification(n_samples=1000, n_features=20, random_state=42)

data = pd.DataFrame(X)
data.insert(0, 'target', y)

train_data, val_data = train_test_split(data, test_size=0.3, random_state=42)

train_data.to_csv('train.csv', header=False, index=False)
val_data.to_csv('validation.csv', header=False, index=False)

train_uri = session.upload_data('train.csv', bucket=bucket, key_prefix=f'{prefix}/train')
val_uri = session.upload_data('validation.csv', bucket=bucket, key_prefix=f'{prefix}/validation')

print("Data uploaded to S3.")

container = sagemaker.image_uris.retrieve("xgboost", region, "latest")

xgb = sagemaker.estimator.Estimator(
    image_uri=container,
    role=role,
    instance_count=1,
    instance_type='ml.m5.large',
    output_path=f's3://{bucket}/{prefix}/output',
    sagemaker_session=session
)

xgb.set_hyperparameters(
    objective='binary:logistic',
    num_round=50,
    eval_metric='auc'
)

hyperparameter_ranges = {
    'eta': ContinuousParameter(0.1, 0.5),           
    'max_depth': IntegerParameter(3, 9),            
    'min_child_weight': IntegerParameter(2, 6)      
}

tuner = HyperparameterTuner(
    estimator=xgb,
    objective_metric_name='validation:auc', 
    hyperparameter_ranges=hyperparameter_ranges,
    max_jobs=6,               
    max_parallel_jobs=2,      
    objective_type='Maximize' 
)

s3_input_train = TrainingInput(s3_data=train_uri, content_type='csv')
s3_input_validation = TrainingInput(s3_data=val_uri, content_type='csv')

print("\nStarting Hyperparameter Tuning Job...")
print("This will take approximately 5-8 minutes. Please wait.")

tuner.fit({'train': s3_input_train, 'validation': s3_input_validation})
tuner.wait()

best_job = tuner.best_training_job()

best_job_details = boto3.client('sagemaker').describe_training_job(TrainingJobName=best_job)
best_params = best_job_details['HyperParameters']
best_score = best_job_details['FinalMetricDataList'][0]['Value']

print("\n------------------------------------------------")
print(f"TUNING COMPLETE")
print(f"Best Training Job: {best_job}")
print(f"Best AUC Score:    {best_score}")
print("Best Hyperparameters Found:")
print(f" - eta:              {best_params.get('eta')}")
print(f" - max_depth:        {best_params.get('max_depth')}")
print(f" - min_child_weight: {best_params.get('min_child_weight')}")
print("------------------------------------------------")
        ''',
        '''
Comprehend
        ''',
        '''
Lex
        ''',
        '''
Rekognition
        ''',
    ]

    @staticmethod
    def text(index):
        """Fetch a specific code based on the index."""
        try:
            return CC.codes[index - 1]
        except IndexError:
            return f"Invalid code index. Please choose a number between 1 and {len(CC.codes)}."
