"""Tests for artifact sandbox and toolkit."""
from __future__ import annotations

import asyncio
import json
from pathlib import Path
import zipfile


from logos_adk.agent import Agent
from logos_adk.artifacts import ArtifactSandbox
from logos_adk.context import RunContext, use_run_context


def test_artifact_sandbox_persists_text_and_json_records(tmp_path):
    sandbox = ArtifactSandbox(tmp_path / "artifacts")

    text_record = sandbox.create_text_artifact(
        workspace_id="acme",
        name="brief",
        content="launch plan",
        created_by="writer",
    )
    json_record = sandbox.create_json_artifact(
        workspace_id="acme",
        name="metrics",
        payload={"ctr": 0.42},
        created_by="analyst",
    )

    listed = sandbox.list_artifacts(workspace_id="acme")

    assert {item.id for item in listed} == {text_record.id, json_record.id}
    assert sandbox.read_text(text_record.id) == "launch plan"
    assert json.loads(sandbox.read_text(json_record.id)) == {"ctr": 0.42}


def test_create_excel_artifact_writes_valid_xlsx_archive(tmp_path):
    sandbox = ArtifactSandbox(tmp_path / "artifacts")

    record = sandbox.create_excel_artifact(
        workspace_id="acme",
        name="weekly_report",
        rows=[
            {"campaign": "spring", "ctr": 0.55},
            {"campaign": "summer", "ctr": 0.61},
        ],
        created_by="analyst",
    )

    path = sandbox.artifact_path(record.id)
    assert path is not None
    assert path.suffix == ".xlsx"
    with zipfile.ZipFile(path, "r") as archive:
        assert "xl/workbook.xml" in archive.namelist()
        sheet_xml = archive.read("xl/worksheets/sheet1.xml").decode("utf-8")
    assert "campaign" in sheet_xml
    assert "spring" in sheet_xml
    assert "0.61" in sheet_xml


def test_agent_artifact_toolkit_uses_workspace_run_context(tmp_path):
    agent = Agent("designer").artifact_sandbox(root=str(tmp_path / "artifacts"))
    tools = {tool.name: tool for tool in agent._config.tools}
    assert {
        "create_text_artifact",
        "generate_diffusion_image_artifact",
        "list_artifacts",
        "read_artifact_text",
    } <= set(tools)

    with use_run_context(RunContext(workspace_id="workspace-42", session_id="s-1")):
        created = asyncio.run(tools["create_text_artifact"](name="notes", content="hello world"))
        listed = asyncio.run(tools["list_artifacts"]())
        text = asyncio.run(tools["read_artifact_text"](artifact_id=created["id"]))

    assert created["workspace_id"] == "workspace-42"
    assert listed[0]["id"] == created["id"]
    assert text == "hello world"


def test_create_video_artifact_uses_ffmpeg_output(tmp_path, monkeypatch):
    sandbox = ArtifactSandbox(tmp_path / "artifacts")
    frame = sandbox.create_text_artifact(
        workspace_id="acme",
        name="frame",
        content="frame placeholder",
        mime_type="image/png",
        extension=".png",
    )

    monkeypatch.setattr("logos_adk.artifacts.shutil.which", lambda name: "/usr/bin/ffmpeg")

    def fake_run(command, capture_output, text, check):
        output_path = Path(command[-1])
        output_path.write_bytes(b"fake-mp4")

        class Result:
            returncode = 0
            stdout = ""
            stderr = ""

        return Result()

    monkeypatch.setattr("logos_adk.artifacts.subprocess.run", fake_run)

    record = sandbox.create_video_artifact(
        workspace_id="acme",
        name="promo_video",
        artifact_ids=[frame.id],
    )

    assert record.kind == "video"
    assert record.mime_type == "video/mp4"
    assert sandbox.artifact_path(record.id) is not None
