# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========

import logging

from mirage.accessor.discord import DiscordAccessor
from mirage.commands.builtin.discord.grep import (SEARCH_HONORED,
                                                  SEARCH_MAX_RESULTS)
from mirage.commands.builtin.discord.io import resolve_glob
from mirage.commands.builtin.generic.rg import rg as generic_rg
from mirage.commands.builtin.generic_bind.adapter import bound_op
from mirage.commands.builtin.grep_helper import pattern_arg, pushdown_operand
from mirage.commands.builtin.utils.output import format_records
from mirage.commands.config import CommandOpts
from mirage.commands.errors import UsageError
from mirage.commands.registry import command
from mirage.commands.spec import SPECS
from mirage.commands.spec.types import FlagView
from mirage.core.discord.channels import list_channels
from mirage.core.discord.entry import channel_dirname
from mirage.core.discord.formatters import format_grep_results
from mirage.core.discord.read import read as discord_read
from mirage.core.discord.readdir import readdir as _readdir
from mirage.core.discord.scope import NATIVE_KINDS, detect_scope
from mirage.core.discord.search import search_guild
from mirage.core.discord.stat import stat as _stat
from mirage.io.types import ByteSource, IOResult
from mirage.types import PathSpec
from mirage.utils.key_prefix import mount_prefix_of

logger = logging.getLogger(__name__)


@command("rg", resource="discord", spec=SPECS["rg"])
async def rg(accessor: DiscordAccessor, paths: list[PathSpec],
             texts: list[str],
             opts: CommandOpts) -> tuple[ByteSource | None, IOResult]:
    fl = FlagView(opts.flags, spec=SPECS["rg"])
    pattern_str = pattern_arg(texts, fl)
    if pattern_str is None:
        raise UsageError("rg: usage: rg [flags] pattern [path]")

    pushdown_warnings: list[str] = []
    # Output-shaping flags, a glob operand and a multi-operand line all need
    # the generic scan; see SEARCH_HONORED above.
    operand = pushdown_operand(paths, opts.flags, pattern_str, SEARCH_HONORED)
    if operand is not None and fl.as_bool("w"):
        match = detect_scope(operand)
        if match.kind in NATIVE_KINDS:
            guild_id = match.slots["guild_id"]
            try:
                msgs = await search_guild(
                    accessor.config,
                    guild_id,
                    pattern_str,
                    channel_id=match.slots.get("channel_id"),
                    limit=SEARCH_MAX_RESULTS,
                )
                file_prefix = mount_prefix_of(operand.virtual,
                                              operand.resource_path) or ""
                resource_first = match.resource_path.strip("/").split("/",
                                                                      1)[0]
                channels = await list_channels(accessor.config, guild_id)
                channel_map = {c["id"]: channel_dirname(c) for c in channels}
                lines = format_grep_results(msgs, file_prefix, resource_first,
                                            channel_map)
                if not lines:
                    return b"", IOResult(exit_code=1)
                return format_records(lines), IOResult()
            except Exception as exc:
                msg = str(exc)
                pushdown_warnings.append(
                    f"discord: native search push-down failed ({msg}); "
                    f"falling back to per-file scan")
                if ("403" in msg or "Forbidden" in msg
                        or "missing access" in msg.lower()):
                    pushdown_warnings.append(
                        "discord: hint - ensure the bot has the "
                        "READ_MESSAGE_HISTORY permission for this guild "
                        "and the MESSAGE CONTENT privileged intent enabled")
                logger.warning(
                    "discord search push-down failed (%s); "
                    "falling back to per-file scan", exc)

    resolved = await resolve_glob(accessor, paths,
                                  index=opts.index) if paths else []
    stdout, io = await generic_rg(
        resolved,
        texts,
        opts.flags,
        readdir=bound_op(_readdir, accessor, opts.index),
        stat=bound_op(_stat, accessor, opts.index),
        read_bytes=bound_op(discord_read, accessor, opts.index),
        read_stream=None,
        stdin=opts.stdin,
    )
    if pushdown_warnings:
        io.stderr = ("\n".join(pushdown_warnings) + "\n").encode()
    return stdout, io
