"""Example 5: Upload Artifacts (files without a model flavour).

Demonstrates how to upload raw files (configs, vectors, CSVs)
to MLflow without registering a model flavour.

This is useful for uploading pre-built artefacts like:
- Pre-computed embedding vectors
- Configuration files
- CSV evaluation results

Run:
    python examples/05_upload_artifacts.py
"""

import csv
import json
import os
import tempfile

from dgtw_mlflow_utils import (
    Architecture,
    ModelUploader,
    ModelVariant,
    RunAction,
    Stage,
    UploadConfig,
)


def main():
    """Run the artifact upload example."""
    # ------------------------------------------------------------------
    # 1) Create some sample artifact files in a temp directory
    # ------------------------------------------------------------------
    tmpdir = tempfile.mkdtemp()

    # Config file
    config_path = os.path.join(tmpdir, "model_config.json")
    with open(config_path, "w") as f:
        json.dump(
            {
                "embedding_dim": 256,
                "num_layers": 4,
                "learning_rate": 0.001,
                "batch_size": 128,
            },
            f,
            indent=2,
        )

    # Evaluation results CSV
    results_path = os.path.join(tmpdir, "eval_results.csv")
    with open(results_path, "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["metric", "value"])
        writer.writerow(["recall@5", 0.82])
        writer.writerow(["mrr", 0.65])
        writer.writerow(["ndcg", 0.71])

    print(f"Created artifact files in: {tmpdir}")
    print(f"  - {config_path}")
    print(f"  - {results_path}")

    # ------------------------------------------------------------------
    # 2) Configure and upload
    # ------------------------------------------------------------------
    config = UploadConfig(
        architecture=Architecture.TWO_TOWER,
        variant=ModelVariant.BASELINE,
        component="Recommendation",
        stage=Stage.RESEARCH,
        use_case="Artifacts",
        action=RunAction.UPLOAD,
        tracking_uri="http://127.0.0.1:5001",
        register_model=False,  # no model registration for raw artifacts
        tags={"artifact_type": "evaluation"},
    )

    uploader = ModelUploader(config)
    print()
    print(uploader.summary())
    print()

    result = uploader.upload_artifacts(
        files=[config_path, results_path],
        artifact_subdir="evaluation",  # stored under evaluation/ in the run
        extra_metrics={
            "recall_5": 0.82,
            "mrr": 0.65,
            "ndcg": 0.71,
        },
    )

    print("Artifact upload successful!")
    print(f"  Run ID         : {result['run_id']}")
    print(f"  Run Name       : {result['run_name']}")
    print(f"  Artifact files : {result['artifact_uris']}")

    # Cleanup temp files
    os.remove(config_path)
    os.remove(results_path)
    os.rmdir(tmpdir)
    print("\nTemp files cleaned up.")


if __name__ == "__main__":
    main()
