"""SLICE-4 — bot multi-file commit + PR primitives."""
from __future__ import annotations

import asyncio

from app import gitea as gitea_mod, metadata
from app.bot import Actor, Bot
from app.config import load_config

from test_propose_vertical import (  # noqa: F401
    app_with_fake_gitea,
    provision_user_row,
    tmp_env,
)

LEGACY = "---\nslug: alpha\ntitle: Alpha\nstate: active\ntags:\n- one\n---\n\nBody.\n"


def _actor():
    return Actor(user_id=1, gitea_login="ben.stull", display_name="Ben", email="ben@x.io")


def test_commit_entry_files_direct_to_main(app_with_fake_gitea):
    _app, fake = app_with_fake_gitea
    gitea = gitea_mod.Gitea(load_config())
    bot = Bot(gitea)
    fake.files[("wiggleverse", "meta", "main", "rfcs/alpha.md")] = {
        "content": LEGACY, "sha": "s1"}
    st = asyncio.run(metadata.read_entry_from_git(gitea, "wiggleverse", "meta", "rfcs/alpha.md"))
    e2 = metadata.apply_values(st.entry, {"tags": ["two"]})
    ops = metadata.write_entry_files("rfcs/alpha.md", e2, st)
    asyncio.run(bot.commit_entry_files(
        _actor(), org="wiggleverse", repo="meta", files=ops,
        message="Edit metadata", branch="main"))
    sc = fake.files[("wiggleverse", "meta", "main", "rfcs/alpha.meta.yaml")]["content"]
    assert "two" in sc
    # .md is now body-only
    assert "---" not in fake.files[("wiggleverse", "meta", "main", "rfcs/alpha.md")]["content"]


def test_open_entry_pr_commits_on_branch_and_opens_pr(app_with_fake_gitea):
    from fastapi.testclient import TestClient

    app, fake = app_with_fake_gitea
    gitea = gitea_mod.Gitea(load_config())
    bot = Bot(gitea)
    fake.files[("wiggleverse", "meta", "main", "rfcs/alpha.md")] = {
        "content": LEGACY, "sha": "s1"}
    with TestClient(app):  # lifespan inits the DB
        provision_user_row(user_id=1, login="ben.stull", role="owner")
        st = asyncio.run(metadata.read_entry_from_git(gitea, "wiggleverse", "meta", "rfcs/alpha.md"))
        e2 = metadata.apply_values(st.entry, {"tags": ["two"]})
        ops = metadata.write_entry_files("rfcs/alpha.md", e2, st)
        pr = asyncio.run(bot.open_entry_pr(
            _actor(), org="wiggleverse", repo="meta", slug="alpha", files=ops,
            pr_title="Metadata: Alpha", pr_description="edit", branch_prefix="metadata"))
    assert pr["number"] >= 1
    head = pr["head"]["ref"]
    assert head.startswith("metadata-alpha-")
    # committed on the branch, main untouched
    assert ("wiggleverse", "meta", head, "rfcs/alpha.meta.yaml") in fake.files
    assert ("wiggleverse", "meta", "main", "rfcs/alpha.meta.yaml") not in fake.files
