from __future__ import annotations

from pathlib import Path
from types import SimpleNamespace

import pytest

from worai.commands import structured_data as sd
from worai.errors import UsageError


def test_resolve_bool_value_and_validate_page(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
    monkeypatch.setattr(sd, "load_profile", lambda _ctx: (SimpleNamespace(settings={"ingest_passthrough_when_html": "yes"}), "p", Path("/tmp/w.toml")))
    assert sd._resolve_bool_value(SimpleNamespace(), None, "ingest.passthrough_when_html") is True

    monkeypatch.setattr(sd, "load_profile", lambda _ctx: (SimpleNamespace(settings={"ingest_passthrough_when_html": "no"}), "p", Path("/tmp/w.toml")))
    assert sd._resolve_bool_value(SimpleNamespace(), None, "ingest.passthrough_when_html") is False

    monkeypatch.setattr(sd, "load_profile", lambda _ctx: (SimpleNamespace(settings={"ingest_passthrough_when_html": "wat"}), "p", Path("/tmp/w.toml")))
    with pytest.raises(UsageError, match="Invalid boolean value"):
        sd._resolve_bool_value(SimpleNamespace(), None, "ingest.passthrough_when_html")

    monkeypatch.setitem(__import__("sys").modules, "wordlift_sdk.validation", SimpleNamespace(list_shape_names=lambda: ["A", "B"]))
    sd.validate_page(url="https://example.com", list_shapes=True)
    out = capsys.readouterr().out
    assert "A" in out and "B" in out


def test_validate_page_error_and_create_generate_inventory(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(sd, "load_profile", lambda _ctx: (_ for _ in ()).throw(ValueError("no profile")))
    monkeypatch.setattr(sd, "validate_jsonld_from_url", lambda *_a, **_k: (_ for _ in ()).throw(RuntimeError("x")))
    with pytest.raises(UsageError, match="Failed to validate JSON-LD"):
        sd.validate_page(
            url="https://example.com",
            shape=None,
            report_file=None,
            format="pretty",
            color=True,
            list_shapes=False,
            headed=False,
            timeout_ms=30000,
            wait_until="networkidle",
            ignore_https_errors=False,
        )

    with pytest.raises(UsageError, match="Schema.org type is required"):
        sd.create(ctx=SimpleNamespace(), url="https://example.com", target_type_arg=None, target_type=None)

    monkeypatch.setattr(sd, "resolve_profile_api_key", lambda _ctx: (_ for _ in ()).throw(ValueError("missing key")))
    with pytest.raises(UsageError, match="missing key"):
        sd.generate(ctx=SimpleNamespace(), input_value="https://example.com/sitemap.xml", yarrrml_path=Path("m.yarrrml"))

    monkeypatch.setattr(sd, "resolve_profile_api_key", lambda _ctx: ("wl", "default", Path("/tmp/w.toml")))

    class _CW:
        def run(self, request, _log):
            assert request.target_type == "Thing"
            return SimpleNamespace(ok=True)

    monkeypatch.setattr(sd, "CreateWorkflow", lambda: _CW())
    sd.create(
        ctx=SimpleNamespace(),
        url="https://example.com",
        target_type_arg="Thing",
        target_type=None,
        output_dir=Path("."),
        base_name="sd",
    )

    class _GW:
        def run(self, request, _log):
            assert request.input_value
            return {"ok": True}

    monkeypatch.setattr(sd, "GenerateWorkflow", lambda: _GW())
    sd.generate(
        ctx=SimpleNamespace(),
        input_value="https://example.com/sitemap.xml",
        yarrrml_path=Path("m.yarrrml"),
    )

    monkeypatch.setattr(sd, "run_inventory", lambda options: [1, 2])
    sd.inventory(
        ctx=SimpleNamespace(),
        source="https://example.com/sitemap.xml",
        sheet_name="Sheet1",
        source_type=None,
        ingest_source="urls",
        ingest_loader="simple",
        ingest_passthrough_when_html=True,
        output="out.csv",
        destination_sheet_id=None,
        destination_sheet_name=None,
        client_secrets=None,
        token=None,
        port=8080,
        timeout=30.0,
        concurrency="auto",
    )


def test_inventory_missing_key(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(sd, "resolve_profile_api_key", lambda _ctx: (None, "default", Path("/tmp/w.toml")))
    with pytest.raises(UsageError, match="WORDLIFT_API_KEY is required"):
        sd.inventory(ctx=SimpleNamespace(), source="https://example.com/sitemap.xml")
