from typing import NamedTuple

import kfp
from kfp.components import InputPath, InputTextFile, OutputPath, OutputTextFile
from kfp.components import func_to_container_op
from kfp_tekton.compiler import TektonCompiler

import os
os.environ["DEFAULT_ACCESSMODES"] = "ReadWriteMany"
os.environ["DEFAULT_STORAGE_SIZE"] = "2Gi"

"""
Explanation: Data passing tutorial
Data passing is the most important aspect of Pipelines.
In Kubeflow Pipelines, the pipeline authors compose pipelines by creating component instances (tasks) and connecting them together.
Component have inputs and outputs. They can consume and produce arbitrary data.
Pipeline authors establish connections between component tasks by connecting their data inputs and outputs - by passing the output of one task as an argument to another task's input.
The system takes care of storing the data produced by components and later passing that data to other components for consumption as instructed by the pipeline.
This tutorial shows how to create python components that produce, consume and transform data.
It shows how to create data passing pipelines by instantiating components and connecting them together.
End of explanation
"""


@func_to_container_op
def print_small_text(text: str):
    '''Print small text'''
    print(text)

def constant_to_consumer_pipeline():
    '''Pipeline that passes small constant string to to consumer'''
    consume_task = print_small_text('Hello world') # Passing constant as argument to consumer

TektonCompiler().compile(constant_to_consumer_pipeline,
                         'constant_to_consumer_pipeline.yaml')

!kubectl apply -f constant_to_consumer_pipeline.yaml

!tkn pr describe constant-to-consumer-pipeline

def pipeline_parameter_to_consumer_pipeline(text: str):
    '''Pipeline that passes small pipeline parameter string to to consumer'''
    consume_task = print_small_text(text) # Passing pipeline parameter as argument to consumer

TektonCompiler().compile(pipeline_parameter_to_consumer_pipeline,
                         'pipeline_parameter_to_consumer_pipeline.yaml')

!kubectl apply -f pipeline_parameter_to_consumer_pipeline.yaml

!tkn pr describe pipeline-parameter-to-consumer-pipeline

"""
Explanation: Small data
Small data is the data that you'll be comfortable passing as program's command-line argument. Small data size should not exceed few kilobytes.
Some examples of typical types of small data are: number, URL, small string (e.g. column name).
Small lists, dictionaries and JSON structures are fine, but keep an eye on the size and consider switching to file-based data passing methods that are more suitable for big data (more than several kilobytes) or binary data.
All small data outputs will be at some point serialized to strings and all small data input values will be at some point deserialized from strings (passed as command-line argumants). There are built-in serializers and deserializers for several common types (e.g. str, int, float, bool, list, dict). All other types of data need to be serialized manually before returning the data. Make sure to properly specify type annotations, otherwize there would be no automatic deserialization and the component function will receive strings instead of deserialized objects.
Consuming small data
End of explanation
"""


@func_to_container_op
def produce_one_small_output() -> str:
    return 'Hello world'

def task_output_to_consumer_pipeline():
    '''Pipeline that passes small data from producer to consumer'''
    produce_task = produce_one_small_output()
    # Passing producer task output as argument to consumer
    consume_task1 = print_small_text(produce_task.output) # task.output only works for single-output components
    consume_task2 = print_small_text(produce_task.outputs['output']) # task.outputs[...] always works

TektonCompiler().compile(task_output_to_consumer_pipeline,
                         'task_output_to_consumer_pipeline.yaml')

!kubectl apply -f task_output_to_consumer_pipeline.yaml

!tkn pr describe task-output-to-consumer-pipeline

"""
Explanation: Producing small data
End of explanation
"""


@func_to_container_op
def produce_two_small_outputs() -> NamedTuple('Outputs', [('text', str), ('number', int)]):
    return ("data 1", 42)

@func_to_container_op
def consume_two_arguments(text: str, number: int):
    print('Text={}'.format(text))
    print('Number={}'.format(str(number)))

def producers_to_consumers_pipeline(text: str = "Hello world"):
    '''Pipeline that passes data from producer to consumer'''
    produce1_task = produce_one_small_output()
    produce2_task = produce_two_small_outputs()

    consume_task1 = consume_two_arguments(produce1_task.output, 42)
    consume_task2 = consume_two_arguments(text, produce2_task.outputs['number'])
    consume_task3 = consume_two_arguments(produce2_task.outputs['text'], produce2_task.outputs['number'])

TektonCompiler().compile(producers_to_consumers_pipeline,
                         'producers_to_consumers_pipeline.yaml')

!kubectl apply -f producers_to_consumers_pipeline.yaml

!tkn pr describe producers-to-consumers-pipeline

"""
Explanation: Producing and consuming multiple arguments
End of explanation
"""


@func_to_container_op
def get_item_from_list(list_of_strings: list, index: int) -> str:
    return list_of_strings[index]

@func_to_container_op
def truncate_text(text: str, max_length: int) -> str:
    return text[0:max_length]

def processing_pipeline(text: str = "Hello world"):
    truncate_task = truncate_text(text, max_length=5)
    get_item_task = get_item_from_list(list_of_strings=[3, 1, truncate_task.output, 1, 5, 9, 2, 6, 7], index=2)
    print_small_text(get_item_task.output)


TektonCompiler().compile(processing_pipeline,
                         'processing_pipeline.yaml')

!kubectl apply -f processing_pipeline.yaml

!tkn pr describe processing-pipeline

"""
Explanation: Consuming and producing data at the same time
End of explanation
"""


# Writing big data
@func_to_container_op
def repeat_line(line: str, output_text_path: OutputPath(str), count: int = 10):
    '''Repeat the line specified number of times'''
    with open(output_text_path, 'w') as writer:
        for i in range(count):
            writer.write(line + '\n')


# Reading big data
@func_to_container_op
def print_text(text_path: InputPath()): # The "text" input is untyped so that any data can be printed
    '''Print text'''
    with open(text_path, 'r') as reader:
        for line in reader:
            print(line, end = '')

def print_repeating_lines_pipeline():
    repeat_lines_task = repeat_line(line='Hello', count=5000)
    print_text(repeat_lines_task.output) # Don't forget .output !

TektonCompiler().compile(print_repeating_lines_pipeline,
                         'print_repeating_lines_pipeline.yaml')

!kubectl apply -f print_repeating_lines_pipeline.yaml

!tkn pr describe print-repeating-lines-pipeline

"""
Explanation: big data (files)
big data should be read from files and written to files.
The paths for the input and output files are chosen by the system and are passed into the function (as strings).
Use the InputPath parameter annotation to tell the system that the function wants to consume the corresponding input data as a file. The system will download the data, write it to a local file and then pass the path of that file to the function.
Use the OutputPath parameter annotation to tell the system that the function wants to produce the corresponding output data as a file. The system will prepare and pass the path of a file where the function should write the output data. After the function exits, the system will upload the data to the storage system so that it can be passed to downstream components.
You can specify the type of the consumed/produced data by specifying the type argument to InputPath and OutputPath. The type can be a python type or an arbitrary type name string. OutputPath('TFModel') means that the function states that the data it has written to a file has type 'TFModel'. InputPath('TFModel') means that the function states that it expect the data it reads from a file to have type 'TFModel'. When the pipeline author connects inputs to outputs the system checks whether the types match.
Note on input/output names: When the function is converted to component, the input and output names generally follow the parameter names, but the "_path" and "_file" suffixes are stripped from file/path inputs and outputs. E.g. the number_file_path: InputPath(int) parameter becomes the number: int input. This makes the argument passing look more natural: number=42 instead of number_file_path=42.
Notes: As we used 'workspaces' in Tekton pipelines to handle big data processing, the compiler will generate the PVC definitions and needs the volume to store the data.
User need to create volume manually, or enable dynamic volume provisioning, refer to the link of:
https://kubernetes.io/docs/concepts/storage/dynamic-provisioning
Writing and reading big data
End of explanation
"""


@func_to_container_op
def split_text_lines(source_path: InputPath(str), odd_lines_path: OutputPath(str), even_lines_path: OutputPath(str)):
    with open(source_path, 'r') as reader:
        with open(odd_lines_path, 'w') as odd_writer:
            with open(even_lines_path, 'w') as even_writer:
                while True:
                    line = reader.readline()
                    if line == "":
                        break
                    odd_writer.write(line)
                    line = reader.readline()
                    if line == "":
                        break
                    even_writer.write(line)

def text_splitting_pipeline():
    text = '\n'.join(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'])
    split_text_task = split_text_lines(text)
    print_text(split_text_task.outputs['odd_lines'])
    print_text(split_text_task.outputs['even_lines'])

TektonCompiler().compile(text_splitting_pipeline,
                         'text_splitting_pipeline.yaml')

!kubectl apply -f text_splitting_pipeline.yaml

!tkn pr describe text-splitting-pipeline

"""
Explanation: Processing big data
End of explanation
"""


@func_to_container_op
def split_text_lines2(source_file: InputTextFile(str), odd_lines_file: OutputTextFile(str), even_lines_file: OutputTextFile(str)):
    while True:
        line = source_file.readline()
        if line == "":
            break
        odd_lines_file.write(line)
        line = source_file.readline()
        if line == "":
            break
        even_lines_file.write(line)

def text_splitting_pipeline2():
    text = '\n'.join(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'])
    split_text_task = split_text_lines2(text)
    print_text(split_text_task.outputs['odd_lines']).set_display_name('Odd lines')
    print_text(split_text_task.outputs['even_lines']).set_display_name('Even lines')

TektonCompiler().compile(text_splitting_pipeline2,
                         'text_splitting_pipeline2.yaml')

!kubectl apply -f text_splitting_pipeline2.yaml

!tkn pr describe text-splitting-pipeline2

"""
Explanation: Processing big data with pre-opened files
End of explanation
"""


# Writing many numbers
@func_to_container_op
def write_numbers(numbers_path: OutputPath(str), start: int = 0, count: int = 10):
    with open(numbers_path, 'w') as writer:
        for i in range(start, count):
            writer.write(str(i) + '\n')


# Reading and summing many numbers
@func_to_container_op
def sum_numbers(numbers_path: InputPath(str)) -> int:
    sum = 0
    with open(numbers_path, 'r') as reader:
        for line in reader:
            sum = sum + int(line)
    return sum



# Pipeline to sum 100000 numbers
def sum_pipeline(count: 'Integer' = 100000):
    numbers_task = write_numbers(count=count)
    print_text(numbers_task.output)

    sum_task = sum_numbers(numbers_task.outputs['numbers'])
    print_text(sum_task.output)

TektonCompiler().compile(sum_pipeline,
                         'sum_pipeline.yaml')

!kubectl apply -f sum_pipeline.yaml

!tkn pr describe sum-pipeline

"""
Explanation: Example: Pipeline that generates then sums many numbers
End of explanation
"""


