import io
from pathlib import Path
import zipfile

from src.ai.skills.base import SkillsManager


def _build_codex_skill_zip_bytes(markdown_text: str, root_name: str = "Humanizer-zh-main") -> bytes:
    buffer = io.BytesIO()
    with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(f"{root_name}/SKILL.md", markdown_text)
    return buffer.getvalue()


def test_resolve_network_source_supports_github_git_url(tmp_path: Path):
    manager = SkillsManager(tmp_path / "skills")
    url, hint_key, subpath = manager._resolve_network_source(
        "https://github.com/op7418/Humanizer-zh.git"
    )

    assert url == "https://codeload.github.com/op7418/Humanizer-zh/zip/refs/heads/main"
    assert hint_key == "humanizer_zh"
    assert subpath is None


def test_install_skill_from_local_skill_markdown_source(tmp_path: Path):
    source_dir = tmp_path / "Humanizer-zh-main"
    source_dir.mkdir(parents=True, exist_ok=True)
    (source_dir / "SKILL.md").write_text(
        "# Humanizer-zh\n\nUse natural and human-like Chinese tone.\n",
        encoding="utf-8",
    )

    manager = SkillsManager(tmp_path / "skills")
    ok, installed_key = manager.install_skill_from_source(str(source_dir), skill_name="humanizer_zh")

    assert ok
    assert installed_key == "humanizer_zh"
    installed_dir = tmp_path / "skills" / "humanizer_zh"
    assert (installed_dir / "skill.json").exists()
    assert (installed_dir / "main.py").exists()
    assert (installed_dir / "SKILL.md").exists()

    main_code = (installed_dir / "main.py").read_text(encoding="utf-8")
    assert "read_skill_doc" in main_code
    skill_text = (installed_dir / "SKILL.md").read_text(encoding="utf-8")
    assert "Humanizer-zh" in skill_text


def test_install_skill_from_github_git_url_uses_repo_zip_and_markdown_adapter(
    tmp_path: Path, monkeypatch
):
    manager = SkillsManager(tmp_path / "skills")
    zip_bytes = _build_codex_skill_zip_bytes(
        "# Humanizer-zh\n\nUse natural and human-like Chinese tone.\n"
    )
    captured_urls = []

    def fake_download(url: str, output_zip: Path):
        captured_urls.append(url)
        output_zip.write_bytes(zip_bytes)

    monkeypatch.setattr(manager, "_download_zip", fake_download)

    ok, installed_key = manager.install_skill_from_source(
        "https://github.com/op7418/Humanizer-zh.git"
    )

    assert ok
    assert installed_key == "humanizer_zh"
    assert captured_urls == [
        "https://codeload.github.com/op7418/Humanizer-zh/zip/refs/heads/main"
    ]
    assert (tmp_path / "skills" / "humanizer_zh" / "SKILL.md").exists()
