# --- Part 3.1: Project Structure ---
p31 = """# Project Structure (Create these files manually)

PRAC_3/
│── artifacts/
│
│── data/
│   └── iris_v1.csv
│
│── src/
│   ├── create_data.py
│   └── train.py
│
│── requirements.txt
│── README.md
"""

# --- Part 3.2: requirements.txt ---
p32 = """# File: requirements.txt

pandas
scikit-learn
mlflow
matplotlib
"""

# --- Part 3.3: src/create_data.py ---
p33 = """# File: src/create_data.py

from sklearn.datasets import load_iris
import pandas as pd 

iris = load_iris()
df = load_iris(as_frame=True).frame

df.to_csv("data/iris_v1.csv", index=False)

print("Data created and saved to data/iris_v1.csv")
"""

# --- Part 3.4: src/train.py ---
p34 = """# File: src/train.py

import pandas as pd
import mlflow
import mlflow.sklearn
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, confusion_matrix
import matplotlib.pyplot as plt
import os

# Load data
data = pd.read_csv("data/iris_v1.csv")

X = data.drop("target", axis=1)
y = data["target"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=69)

# Parameters (change these for experiments)
n_estimators = 500
max_depth = 250

# Start MLflow experiment
mlflow.set_experiment("Iris-Classification")

with mlflow.start_run():

    # Log parameters
    mlflow.log_param("n_estimators", n_estimators)
    mlflow.log_param("max_depth", max_depth)

    # Train model
    model = RandomForestClassifier(
        n_estimators=n_estimators,
        max_depth=max_depth,
        random_state=69
    )
    model.fit(X_train, y_train)

    # Predictions
    y_pred = model.predict(X_test)

    # Metrics
    acc = accuracy_score(y_test, y_pred)
    prec = precision_score(y_test, y_pred, average="macro")
    rec = recall_score(y_test, y_pred, average="macro")

    mlflow.log_metric("accuracy", acc)
    mlflow.log_metric("precision", prec)
    mlflow.log_metric("recall", rec)

    # Confusion matrix
    cm = confusion_matrix(y_test, y_pred)
    plt.imshow(cm)
    plt.title("Confusion Matrix")
    plt.colorbar()
    plt.xlabel("Predicted")
    plt.ylabel("Actual")

    os.makedirs("artifacts", exist_ok=True)
    cm_path = "artifacts/confusion_matrix.png"
    plt.savefig(cm_path)

    mlflow.log_artifact(cm_path)

    # Log model
    mlflow.sklearn.log_model(model, "model")

    print("Run completed")
"""

# --- Part 3.5: README.md ---
p35 = """# File: README.md

# MLOps Project – Practical 3

This project demonstrates how to use MLflow for Data Versioning and Experiment Tracking.

## Steps
1. Data ingestion
2. Model training
3. Run MLflow UI for experiment tracking

## How to run
python src/create_data.py
python src/train.py   # Run multiple times
mlflow ui
"""