from __future__ import annotations

from types import SimpleNamespace

import oasyce.services.source_asset_policy as source_asset_policy
from oasyce.services.source_asset_policy import resolve_source_asset_pricing


class _FakeResponse:
    def __init__(self, status: int = 200):
        self.status = status

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        return False


def test_public_git_open_source_source_defaults_to_free(monkeypatch, tmp_path):
    repo = tmp_path / "repo"
    repo.mkdir()
    (repo / ".git").mkdir()
    (repo / "LICENSE").write_text("MIT License", encoding="utf-8")
    source_file = repo / "main.py"
    source_file.write_text("print('hello')\n", encoding="utf-8")

    monkeypatch.setattr(
        source_asset_policy.subprocess,
        "run",
        lambda *args, **kwargs: SimpleNamespace(
            returncode=0, stdout="https://github.com/acme/demo.git\n"
        ),
    )
    monkeypatch.setattr(
        source_asset_policy.urllib.request,
        "urlopen",
        lambda *args, **kwargs: _FakeResponse(200),
    )

    decision = resolve_source_asset_pricing(str(source_file), requested_price_model="auto")

    assert decision.resolved_price_model == "free"
    assert decision.reason == "public_git_open_source_defaults_free"
    assert decision.metadata["source_origin"] == "public_git_open_source"
    assert decision.metadata["source_repo_url"] == "https://github.com/acme/demo"
    assert decision.metadata["source_license"] == "mit"


def test_non_source_file_keeps_auto(monkeypatch, tmp_path):
    repo = tmp_path / "repo"
    repo.mkdir()
    (repo / ".git").mkdir()
    (repo / "LICENSE").write_text("MIT License", encoding="utf-8")
    source_file = repo / "preview.png"
    source_file.write_bytes(b"png")

    monkeypatch.setattr(
        source_asset_policy.subprocess,
        "run",
        lambda *args, **kwargs: SimpleNamespace(
            returncode=0, stdout="https://github.com/acme/demo.git\n"
        ),
    )

    decision = resolve_source_asset_pricing(str(source_file), requested_price_model="auto")

    assert decision.resolved_price_model == "auto"
    assert decision.reason is None
    assert decision.metadata == {}


def test_missing_open_source_license_keeps_auto(monkeypatch, tmp_path):
    repo = tmp_path / "repo"
    repo.mkdir()
    (repo / ".git").mkdir()
    source_file = repo / "main.py"
    source_file.write_text("print('hello')\n", encoding="utf-8")

    monkeypatch.setattr(
        source_asset_policy.subprocess,
        "run",
        lambda *args, **kwargs: SimpleNamespace(
            returncode=0, stdout="https://github.com/acme/demo.git\n"
        ),
    )

    decision = resolve_source_asset_pricing(str(source_file), requested_price_model="auto")

    assert decision.resolved_price_model == "auto"
    assert decision.reason is None
    assert decision.metadata == {}
