"""Test that SkillBase loads each skill's module independently (no sys.modules cache collision)."""

import os

import pytest
import yaml

from fliiq.runtime.skills.base import SkillBase


def _make_skill(tmp_path: str, name: str, return_value: str) -> str:
    """Create a minimal skill directory with SKILL.md + fliiq.yaml + main.py."""
    skill_dir = os.path.join(tmp_path, name)
    os.makedirs(skill_dir)

    # SKILL.md
    with open(os.path.join(skill_dir, "SKILL.md"), "w") as f:
        f.write(f"---\nname: {name}\ndescription: \"Test skill {name}\"\n---\n\nTest.\n")

    # fliiq.yaml
    config = {
        "input_schema": {"type": "object", "properties": {}},
        "output_schema": {"type": "object", "properties": {"result": {"type": "string", "description": "test"}}},
    }
    with open(os.path.join(skill_dir, "fliiq.yaml"), "w") as f:
        yaml.dump(config, f)

    # main.py — returns a unique value per skill
    with open(os.path.join(skill_dir, "main.py"), "w") as f:
        f.write(f"def handler(params):\n    return {{'result': '{return_value}'}}\n")

    return skill_dir


def test_no_module_cache_collision(tmp_path):
    """Two skills with handler in main.py must load their own handler, not share a cached one."""
    dir_a = _make_skill(str(tmp_path), "skill_a", "from_a")
    dir_b = _make_skill(str(tmp_path), "skill_b", "from_b")

    a = SkillBase(dir_a)
    b = SkillBase(dir_b)

    assert a._handler({}) == {"result": "from_a"}
    assert b._handler({}) == {"result": "from_b"}


def test_skill_metadata():
    """Smoke test: real get_current_time skill loads metadata correctly."""
    from fliiq.runtime.package_data import bundled_skills_dir

    skill_dir = str(bundled_skills_dir() / "time")
    skill = SkillBase(skill_dir)
    assert skill.name == "get_current_time"
    assert "timezone" in skill.schema()["parameters"]["properties"]
