from __future__ import annotations

import json

import pytest

from app.config import Settings
from app.pending_changes import PendingChangeError, PendingChangeRepository, ProposedChangeRequest
from app.validation import scan_text_for_secrets


def _copy_schema_files(tmp_path) -> None:
    (tmp_path / "schemas").mkdir()
    source_schema = Settings().repo_root / "schemas"
    for schema in source_schema.glob("*.json"):
        (tmp_path / "schemas" / schema.name).write_text(schema.read_text(), encoding="utf-8")


def _create_empty_inventory(tmp_path) -> None:
    (tmp_path / "40-inventory").mkdir()
    for name in [
        "backups",
        "databases",
        "domains",
        "endpoints",
        "hardware",
        "hosts",
        "integrations",
        "networks",
        "projects",
        "services",
        "traffic-routes",
        "virtual-machines",
    ]:
        (tmp_path / "40-inventory" / f"{name}.yml").write_text("---\n[]\n", encoding="utf-8")


def test_scan_text_for_secrets_detects_assignment() -> None:
    messages = scan_text_for_secrets("password: hunter2\n")
    assert len(messages) == 1
    assert "line 1" in messages[0]
    assert "hunter2" not in messages[0]


def test_scan_text_for_secrets_allows_safe_references() -> None:
    assert scan_text_for_secrets("password: secret reference\n") == []
    assert scan_text_for_secrets("token: none\n") == []


def test_create_rejects_secret_payload_without_writing_file(tmp_path) -> None:
    repo = PendingChangeRepository(Settings(tmp_path))
    request = ProposedChangeRequest(
        kind="doc",
        target="10-systems/example.md",
        summary="Poison the queue",
        payload={"content": "---\nowner: gmikcon\nstatus: active\nlast_reviewed: 2026-05-09\nreview_interval: 90d\nconfidence: medium\nsource_of_truth: test\n---\n\npassword: hunter2\n"},
    )

    with pytest.raises(PendingChangeError, match="possible secret"):
        repo.create(request)

    assert list((tmp_path / "90-maintenance" / "pending-changes").glob("*.json")) == []


def test_create_rejects_doc_target_escape(tmp_path) -> None:
    repo = PendingChangeRepository(Settings(tmp_path))
    request = ProposedChangeRequest(
        kind="doc",
        target="../outside.md",
        summary="Escape attempt",
        payload={"content": "# Outside\n"},
    )

    with pytest.raises(PendingChangeError, match="escapes repository root"):
        repo.create(request)

    assert list((tmp_path / "90-maintenance" / "pending-changes").glob("*.json")) == []


def test_failed_apply_removes_pending_file(tmp_path, monkeypatch) -> None:
    _copy_schema_files(tmp_path)
    _create_empty_inventory(tmp_path)
    from app import pending_changes as pc

    monkeypatch.setattr(pc, "validate_repository", lambda settings: {"status": "issues", "issue_count": 1, "issues": [{"path": "x", "code": "test", "message": "forced failure"}]})
    repo = PendingChangeRepository(Settings(tmp_path))
    created = repo.create(
        ProposedChangeRequest(
            kind="doc",
            target="10-systems/example.md",
            summary="Add example doc",
            payload={"content": "---\nowner: gmikcon\nstatus: active\nlast_reviewed: 2026-05-09\nreview_interval: 90d\nconfidence: medium\nsource_of_truth: test\n---\n\n# Example\n"},
        )
    )
    pending_file = tmp_path / "90-maintenance" / "pending-changes" / f"{created['id']}.json"
    assert pending_file.exists()

    with pytest.raises(PendingChangeError, match="failed validation"):
        repo.apply(created["id"])

    assert not pending_file.exists()


def test_delete_pending_change(tmp_path) -> None:
    repo = PendingChangeRepository(Settings(tmp_path))
    created = repo.create(
        ProposedChangeRequest(
            kind="inventory-item",
            target="virtual-machines/gnauth",
            summary="Update gnauth",
            payload={"runs_services": ["gnexus-auth"]},
        )
    )

    result = repo.delete(created["id"])
    assert result == {"id": created["id"], "status": "deleted"}
    assert not (tmp_path / "90-maintenance" / "pending-changes" / f"{created['id']}.json").exists()

    with pytest.raises(PendingChangeError, match="not found"):
        repo.delete(created["id"])


def test_delete_refuses_applied_change(tmp_path) -> None:
    _copy_schema_files(tmp_path)
    _create_empty_inventory(tmp_path)
    repo = PendingChangeRepository(Settings(tmp_path))
    created = repo.create(
        ProposedChangeRequest(
            kind="doc",
            target="10-systems/example.md",
            summary="Add example doc",
            payload={"content": "---\nowner: gmikcon\nstatus: active\nlast_reviewed: 2026-05-09\nreview_interval: 90d\nconfidence: medium\nsource_of_truth: test\n---\n\n# Example\n"},
        )
    )
    repo.apply(created["id"])

    with pytest.raises(PendingChangeError, match="Only pending or corrupt"):
        repo.delete(created["id"])


def test_list_tolerates_corrupt_json(tmp_path) -> None:
    repo = PendingChangeRepository(Settings(tmp_path))
    created = repo.create(
        ProposedChangeRequest(
            kind="inventory-item",
            target="virtual-machines/gnauth",
            summary="Update gnauth",
            payload={"runs_services": ["gnexus-auth"]},
        )
    )
    corrupt = tmp_path / "90-maintenance" / "pending-changes" / "20260101000000-deadbeef.json"
    corrupt.write_text("{not valid json", encoding="utf-8")

    changes = repo.list()
    statuses = {change["id"]: change["status"] for change in changes}
    assert statuses[created["id"]] == "pending"
    assert statuses["20260101000000-deadbeef"] == "corrupt"

    with pytest.raises(PendingChangeError, match="corrupt"):
        repo.get("20260101000000-deadbeef")

    with pytest.raises(PendingChangeError, match="corrupt"):
        repo.apply("20260101000000-deadbeef")

    result = repo.delete("20260101000000-deadbeef")
    assert result == {"id": "20260101000000-deadbeef", "status": "deleted"}


def test_happy_path_create_apply_still_works(tmp_path) -> None:
    _copy_schema_files(tmp_path)
    _create_empty_inventory(tmp_path)
    repo = PendingChangeRepository(Settings(tmp_path))
    created = repo.create(
        ProposedChangeRequest(
            kind="doc",
            target="10-systems/example.md",
            summary="Add example doc",
            payload={"content": "---\nowner: gmikcon\nstatus: active\nlast_reviewed: 2026-05-09\nreview_interval: 90d\nconfidence: medium\nsource_of_truth: test\n---\n\n# Example\n"},
        )
    )

    applied = repo.apply(created["id"])
    assert applied["status"] == "applied"
    assert (tmp_path / "10-systems" / "example.md").exists()