import asyncio
from contextlib import nullcontext
import io
import json
import os
import re
import subprocess
import time
from dataclasses import dataclass, field
from pathlib import Path
import discord
from discord.ext import commands, tasks

from .config import load_and_scrub_config
from .git_ops import (
    prepare_branch,
    resume_branch,
    commit_push_and_pr,
    has_changes,
    cleanup_branch,
    _git_env,
    setup_global_git_config,
    get_diff_stat,
)
from .preview import deploy_preview, list_previews, stop_preview
from .remote_control import (
    ensure_remote_control,
    get_remote_control_status,
    start_remote_control,
    stop_remote_control,
    restart_remote_control,
)
from .runners.copilot import CopilotRunner
from .runners.agy import AgyRunner, DEFAULT_MODEL as DEFAULT_GEMINI_MODEL
from .runners.claude import ClaudeRunner
from .quota import get_agy_quota, format_quota_summary, format_quota_embed

CONFIG = load_and_scrub_config()
RUNNERS = {
    "copilot": CopilotRunner(token=CONFIG.gh_token),
    "agy": AgyRunner(),
    "claude": ClaudeRunner(),
}

AVAILABLE_MODELS = [
    "Gemini 3.8 Flash (Medium)",
    "Gemini 3.8 Flash (High)",
    "Gemini 3.8 Flash (Low)",
    "Gemini 4 Neon (Medium)",
    "Gemini 4 Neon (High)",
    "Gemini 4 Neon (Low)",
    "Gemini 4 Carbon (Medium)",
    "Claude Sonnet 5.5 (Medium)",
    "Claude Sonnet 5.5 (High)",
    "Claude Opus 5.5 (Medium)",
    "GPT-OSS 120B (Medium)",
]

# thread_id -> tuple
FAILED_TASKS: dict[int, tuple] = {}


@dataclass
class ThreadSession:
    thread_id: int
    target_repo: str
    branch: str
    session_id: str | None = None
    updated_at: float = field(default_factory=time.time)

    def to_dict(self) -> dict:
        return {
            "thread_id": self.thread_id,
            "target_repo": self.target_repo,
            "branch": self.branch,
            "session_id": self.session_id,
            "updated_at": self.updated_at,
        }

    @classmethod
    def from_dict(cls, data: dict) -> "ThreadSession":
        return cls(
            thread_id=int(data["thread_id"]),
            target_repo=str(data["target_repo"]),
            branch=str(data["branch"]),
            session_id=data.get("session_id"),
            updated_at=float(data.get("updated_at", time.time())),
        )


def _default_sessions_file() -> Path:
    env_path = os.environ.get("THREAD_SESSIONS_FILE")
    if env_path:
        return Path(env_path)
    try:
        agent_dir = Path("/home/agent")
        if agent_dir.is_dir():
            return agent_dir / ".mipilot_thread_sessions.json"
    except (PermissionError, OSError):
        pass
    return Path.home() / ".mipilot_thread_sessions.json"


THREAD_SESSIONS_FILE = _default_sessions_file()
THREAD_SESSIONS: dict[int, ThreadSession] = {}


def load_thread_sessions() -> None:
    global THREAD_SESSIONS
    try:
        if not THREAD_SESSIONS_FILE.exists():
            return
        data = json.loads(THREAD_SESSIONS_FILE.read_text(encoding="utf-8"))
        if isinstance(data, dict):
            for k, v in data.items():
                THREAD_SESSIONS[int(k)] = ThreadSession.from_dict(v)
    except Exception as e:
        print(f"[ThreadSessions] Nepodařilo se načíst relace vláken: {e}")


def save_thread_sessions() -> None:
    try:
        data = {str(k): v.to_dict() for k, v in THREAD_SESSIONS.items()}
        THREAD_SESSIONS_FILE.write_text(json.dumps(data, indent=2), encoding="utf-8")
    except Exception as e:
        print(f"[ThreadSessions] Nepodařilo se uložit relace vláken: {e}")


load_thread_sessions()

MODEL_LIMITS = {
    "Gemini 3.8 Flash (Medium)": {
        "name": "Gemini 3.8 Flash (Medium) (výchozí)",
        "tier_free": "15 RPM • 1 000 000 TPM • 1 500 RPD",
        "tier_paid": "1 000 – 2 000 RPM • 4 000 000 TPM • Neomezeno RPD",
        "desc": "Výchozí rychlý model pro běžné kódovací úkoly v agy.",
    },
    "Gemini 3.8 Flash (High)": {
        "name": "Gemini 3.8 Flash (High)",
        "tier_free": "15 RPM • 1 000 000 TPM • 1 500 RPD",
        "tier_paid": "1 000 – 2 000 RPM • 4 000 000 TPM • Neomezeno RPD",
        "desc": "Flash model s vyšším reasoning effortem.",
    },
    "Gemini 3.8 Flash (Low)": {
        "name": "Gemini 3.8 Flash (Low)",
        "tier_free": "15 RPM • 1 000 000 TPM • 1 500 RPD",
        "tier_paid": "1 000 – 2 000 RPM • 4 000 000 TPM • Neomezeno RPD",
        "desc": "Nejrychlejší Flash model s minimálním reasoningem.",
    },
    "Gemini 4 Neon (Medium)": {
        "name": "Gemini 4 Neon (Medium)",
        "tier_free": "2 RPM • 32 000 TPM • 50 RPD",
        "tier_paid": "360 – 1 000 RPM • 4 000 000 TPM • Neomezeno RPD",
        "desc": "Výkonný model nové generace pro komplexní architekturu a refaktoring.",
    },
    "Gemini 4 Neon (High)": {
        "name": "Gemini 4 Neon (High)",
        "tier_free": "2 RPM • 32 000 TPM • 50 RPD",
        "tier_paid": "360 – 1 000 RPM • 4 000 000 TPM • Neomezeno RPD",
        "desc": "Maximální uvažování pro nejsložitější úkoly.",
    },
    "Gemini 4 Carbon (Medium)": {
        "name": "Gemini 4 Carbon (Medium)",
        "tier_free": "Dle tarifu",
        "tier_paid": "Dle tarifu",
        "desc": "Alternativní vyvážený model Gemini 4.",
    },
    "Claude Sonnet 5.5 (Medium)": {
        "name": "Claude Sonnet 5.5 (Medium)",
        "tier_free": "Dle Anthropic účtu",
        "tier_paid": "Dle Anthropic účtu",
        "desc": "Claude model integrovaný v agy.",
    },
    "GPT-OSS 120B (Medium)": {
        "name": "GPT-OSS 120B (Medium)",
        "tier_free": "Dle nastavení",
        "tier_paid": "Dle nastavení",
        "desc": "Open-source 120B model.",
    },
}

PROVIDER_LIMITS = {
    "copilot": (
        "**GitHub Copilot CLI (`@github/copilot`)**\n"
        "• Limit: Dán GitHub předplatným (Copilot Pro / Business)\n"
        "• Běžně: cca 20–30 volání/minutu, standardní FUP limit účtu."
    ),
    "agy": (
        "**Google Antigravity CLI / Gemini API**\n"
        "• Řídí se nastaveným modelem (`!model`) a plánem v Google AI Studio.\n"
        "• Free Tier: Flash 15 RPM, Pro jen 2 RPM.\n"
        "• Pay-As-You-Go: 360 až 2 000 RPM."
    ),
    "claude": (
        "**Claude Code CLI (`claude`)**\n"
        "• Anthropic API Tier 1: 50 RPM • 20 000 TPM\n"
        "• Anthropic API Tier 2+: 1 000 RPM • 80 000+ TPM"
    ),
}

ANSI_ESCAPE = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")


def strip_ansi(text: str) -> str:
    """Odstraní ANSI escape sekvence (barvy z terminálu)."""
    return ANSI_ESCAPE.sub("", text)


def chunk_text(text: str, max_chunk_size: int = 1900) -> list[str]:
    """Rozdělí text na menší bloky podle nových řádků bez překročení limitu."""
    chunks = []
    while text:
        if len(text) <= max_chunk_size:
            chunks.append(text)
            break
        split_idx = text.rfind("\n", 0, max_chunk_size)
        if split_idx == -1 or split_idx < max_chunk_size // 2:
            split_idx = max_chunk_size
        chunks.append(text[:split_idx])
        text = text[split_idx:].lstrip("\r\n")
    return chunks


async def send_agent_output(
    channel_or_thread: discord.abc.Messageable,
    output: str,
    title: str = "🤖 **Výstup z LLM / agenta:**"
) -> None:
    """Bezpečně pošle výstup z LLM/agenta na Discord s ohledem na limit zpráv (2000 znaků)."""
    cleaned = strip_ansi(output).strip()
    if not cleaned:
        return

    header = f"{title}\n"
    max_len = 1950

    # 1. Vejde se do jedné zprávy
    if len(header) + len(cleaned) <= max_len:
        await channel_or_thread.send(f"{header}{cleaned}")
        return

    # 2. Velmi dlouhý výstup (> 3500 znaků, např. obří log z kompilace/CLI) -> pošleme jako soubor + ukázku
    if len(cleaned) > 3500:
        file = discord.File(io.BytesIO(cleaned.encode("utf-8")), filename="agent_output.txt")
        snippet = cleaned[:800] + "\n\n... [výstup zkrácen, kompletní výpis je přiložen v souboru] ...\n\n" + cleaned[-800:]
        await channel_or_thread.send(
            f"{header}*(výstup je příliš dlouhý, kompletní text je v přiloženém souboru):*\n```\n{snippet}\n```",
            file=file
        )
        return

    # 3. Středně dlouhý výstup (do 3500 znaků) -> rozdělíme do 2 zpráv
    chunks = chunk_text(cleaned, max_len - len(header) if len(header) < max_len else max_len)
    for i, chunk in enumerate(chunks):
        if i == 0:
            await channel_or_thread.send(f"{header}{chunk}")
        else:
            await channel_or_thread.send(chunk)

async def run_agent_workflow(
    thread: discord.abc.Messageable,
    repo_path: Path,
    target_repo: str,
    prompt: str,
    user_id: int,
    session_id: str | None = None,
    existing_branch: str | None = None,
) -> None:
    """Spustí úkol v repozitáři, zpracuje výsledek a v případě chyby umožní opakování."""
    current_model = os.environ.get("GEMINI_MODEL", DEFAULT_GEMINI_MODEL)
    thread_id = getattr(thread, "id", None)

    if existing_branch:
        sess_desc = f" (relace `{session_id[:8]}...`)" if session_id else ""
        await thread.send(
            f"🔄 **mipilot** (`{CONFIG.agent_provider}` / model `{current_model}`) "
            f"navazuje na session{sess_desc} ve větvi `{existing_branch}`..."
        )
    else:
        await thread.send(
            f"🚀 **mipilot** (`{CONFIG.agent_provider}` / model `{current_model}`) "
            f"začíná pracovat na repozitáři `{target_repo}` (nová session)..."
        )

    branch = None
    try:
        typing_cm = thread.typing() if hasattr(thread, "typing") and callable(thread.typing) else nullcontext()
        async with typing_cm:
            if existing_branch:
                branch = await asyncio.to_thread(
                    resume_branch, repo_path, existing_branch, CONFIG.git_author_name, CONFIG.git_author_email, CONFIG.gh_token
                )
            else:
                branch = await asyncio.to_thread(
                    prepare_branch, repo_path, prompt, CONFIG.git_author_name, CONFIG.git_author_email, CONFIG.gh_token
                )

            runner = RUNNERS[CONFIG.agent_provider]
            result = await asyncio.to_thread(runner.run_task, repo_path, prompt, session_id=session_id)

        # 1. Výstup z agenta / LLM vždy vypíšeme na Discord
        if result.output and result.output.strip():
            title = "🤖 **Výstup z LLM / agenta:**" if result.success else "❌ **Výstup agenta (chyba):**"
            await send_agent_output(thread, result.output, title=title)

        # Načteme zbývající kvóty agy (pokud je provider agy)
        quota_summary = ""
        if CONFIG.agent_provider == "agy":
            try:
                quota_groups = await asyncio.to_thread(get_agy_quota)
                if quota_groups:
                    quota_summary = format_quota_summary(quota_groups)
            except Exception:
                pass

        # 2. Pokud běh agenta selhal
        if not result.success:
            if thread_id:
                FAILED_TASKS[thread_id] = (repo_path, target_repo, prompt, user_id, session_id, branch)

            err_msg = (
                "❌ **Běh agenta skončil s chybou. Žádné změny nebyly uloženy.**\n"
                "💡 Pro zobrazení seznamu modelů napiš `!model`, pro přepnutí a opakování `!model <přesný klíč>`."
            )
            if quota_summary:
                err_msg += f"\n\n{quota_summary}"
            await thread.send(err_msg)
            if branch and not existing_branch:
                await asyncio.to_thread(cleanup_branch, repo_path, branch)
            return

        if thread_id:
            FAILED_TASKS.pop(thread_id, None)

        # Uložíme / zaktualizujeme session pro dané vlákno
        new_session_id = result.session_id or session_id
        if thread_id and branch:
            THREAD_SESSIONS[thread_id] = ThreadSession(
                thread_id=thread_id,
                target_repo=target_repo,
                branch=branch,
                session_id=new_session_id,
                updated_at=time.time(),
            )
            save_thread_sessions()

        # 3. Kontrola, zda agent reálně změnil nějaké soubory v repozitáři
        repo_changed = await asyncio.to_thread(has_changes, repo_path)
        if not repo_changed:
            msg = (
                "ℹ️ **Agent neprovedl v repozitáři žádné změny.**\n"
                "Nebyl vytvořen žádný nový Pull Request."
            )
            if quota_summary:
                msg += f"\n\n{quota_summary}"
            await thread.send(msg)
            if branch and not existing_branch:
                await asyncio.to_thread(cleanup_branch, repo_path, branch)
            return

        diff_stat = await asyncio.to_thread(get_diff_stat, repo_path)

        # 4. Nasazení Preview a vytvoření / aktualizace Pull Requestu
        preview_url = await asyncio.to_thread(
            deploy_preview, target_repo, branch, CONFIG.host_repos_path, CONFIG.preview_domain
        )
        pr_url = await asyncio.to_thread(
            commit_push_and_pr, repo_path, branch, prompt, preview_url, CONFIG.gh_token
        )

        embed = discord.Embed(
            title="✅ Úkol dokončen",
            description=f"**Zadání:** {prompt}",
            color=discord.Color.green()
        )
        embed.add_field(name="🔀 Pull Request", value=pr_url, inline=False)
        embed.add_field(name="🌐 Živý náhled (Preview)", value=preview_url, inline=False)
        if diff_stat:
            lines = diff_stat.strip().splitlines()
            if len(lines) > 8:
                display_diff = "\n".join(lines[:7]) + f"\n... ({lines[-1].strip()})"
            else:
                display_diff = diff_stat.strip()
            embed.add_field(name="📝 Změněné soubory", value=f"```\n{display_diff}\n```", inline=False)
        if quota_summary:
            embed.add_field(name="📊 Zbývající kvóty agy", value=quota_summary, inline=False)
        embed.set_footer(text=f"Větev: {branch} • Agent: {CONFIG.agent_provider} • Model: {current_model}")

        await thread.send(embed=embed)
    except Exception as e:
        await thread.send(f"⚠️ Chyba během zpracování: `{str(e)}`")
        if branch and not existing_branch:
            try:
                await asyncio.to_thread(cleanup_branch, repo_path, branch)
            except Exception:
                pass


intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)


def is_authorized(user: discord.User | discord.Member) -> bool:
    return user.id == CONFIG.allowed_user_id


@tasks.loop(minutes=2)
async def remote_control_watchdog():
    """Udržuje Remote Control daemon neustále aktivní na pozadí."""
    try:
        await asyncio.to_thread(ensure_remote_control, CONFIG.remote_control_name)
    except Exception as e:
        print(f"[RemoteControl] Chyba při kontrole daemonu: {e}")


@bot.event
async def on_ready():
    print(f"mipilot připojen na Discord jako {bot.user}")
    try:
        await asyncio.to_thread(
            setup_global_git_config,
            CONFIG.git_author_name,
            CONFIG.git_author_email,
            CONFIG.gh_token,
        )
        print("[GitConfig] Globální konfigurace Gitu a GitHub CLI nastavena.")
    except Exception as e:
        print(f"[GitConfig] Chyba při globální konfiguraci gitu: {e}")

    try:
        success, msg = await asyncio.to_thread(ensure_remote_control, CONFIG.remote_control_name)
        print(f"[RemoteControl] {msg}")
    except Exception as e:
        print(f"[RemoteControl] Chyba při inicializaci: {e}")

    if not remote_control_watchdog.is_running():
        remote_control_watchdog.start()


@bot.command(name="repos")
async def cmd_repos(ctx: commands.Context):
    if not is_authorized(ctx.author):
        return
    repos = [d.name for d in CONFIG.repos_dir.iterdir() if d.is_dir() and not d.name.startswith(".")]
    msg = "**Naklonované repozitáře:**\n" + "\n".join(f"- `{r}`" for r in repos) if repos else "Zatím žádné repozitáře. Použij `!clone <url>`."
    await ctx.send(msg)


@bot.command(name="clone")
async def cmd_clone(ctx: commands.Context, url: str):
    if not is_authorized(ctx.author):
        return
    await ctx.send(f"Klonuji `{url}`...")
    env = _git_env(CONFIG.gh_token)
    subprocess.run(["gh", "auth", "setup-git"], env=env, check=True)
    proc = await asyncio.to_thread(
        subprocess.run, ["git", "clone", url], cwd=CONFIG.repos_dir, env=env, capture_output=True, text=True
    )
    if proc.returncode == 0:
        repo_name = url.rstrip("/").split("/")[-1].removesuffix(".git")
        await ctx.send(f"✅ Repozitář `{repo_name}` naklonován. Vytvoř si pro něj kanál `#{repo_name}` a můžeš psát úkoly přímo tam.")
    else:
        await ctx.send(f"❌ Chyba při klonování:\n```\n{proc.stderr}\n```")


@bot.command(name="provider")
async def cmd_provider(ctx: commands.Context, provider: str | None = None):
    if not is_authorized(ctx.author):
        return
    if provider and provider in RUNNERS:
        CONFIG.agent_provider = provider
        info = PROVIDER_LIMITS.get(provider, "")
        await ctx.send(f"Aktivní agent přepnut na: `{CONFIG.agent_provider}`\n\n{info}")
    else:
        current_info = PROVIDER_LIMITS.get(CONFIG.agent_provider, "")
        await ctx.send(
            f"Aktuální agent: `{CONFIG.agent_provider}`. Dostupné: `copilot`, `agy`, `claude`.\n\n"
            f"**Informace o aktuálním agentovi:**\n{current_info}"
        )


@bot.command(name="model")
async def cmd_model(ctx: commands.Context, *, model: str | None = None):
    if not is_authorized(ctx.author):
        return
    current_model = os.environ.get("GEMINI_MODEL", DEFAULT_GEMINI_MODEL)

    if not model:
        lines = [f"• `{m}`" + (" *(aktivní)*" if m == current_model else "") for m in AVAILABLE_MODELS]
        await ctx.send(
            f"🤖 **Aktuální model:** `{current_model}`\n\n"
            f"📋 **Dostupné modely:**\n" + "\n".join(lines) + "\n\n"
            f"Pro přepnutí zadej: `!model <přesný klíč>`"
        )
        return

    clean_model = model.strip().strip("\"'").strip()
    os.environ["GEMINI_MODEL"] = clean_model

    # Pokud jsme ve vlákně selhaného úkolu, rovnou zopakujeme původní zadání
    if ctx.channel.id in FAILED_TASKS:
        failed_data = FAILED_TASKS.pop(ctx.channel.id)
        repo_path, target_repo, prompt, user_id = failed_data[0], failed_data[1], failed_data[2], failed_data[3]
        session_id = failed_data[4] if len(failed_data) > 4 else None
        existing_branch = failed_data[5] if len(failed_data) > 5 else None

        await ctx.send(
            f"✅ Model nastaven na: `{clean_model}`.\n"
            f"🚀 **Opakuji původní úkol:** *{prompt}*"
        )
        await run_agent_workflow(
            thread=ctx.channel,
            repo_path=repo_path,
            target_repo=target_repo,
            prompt=prompt,
            user_id=user_id,
            session_id=session_id,
            existing_branch=existing_branch,
        )
        return

    await ctx.send(f"✅ Aktivní model nastaven na: `{clean_model}`.")


@bot.command(name="new", aliases=["reset"])
async def cmd_new(ctx: commands.Context):
    """Resetuje navázanou relaci ve vlákně, aby další zpráva začala novou session."""
    if not is_authorized(ctx.author):
        return
    thread_id = ctx.channel.id
    if thread_id in THREAD_SESSIONS:
        THREAD_SESSIONS.pop(thread_id, None)
        save_thread_sessions()
        await ctx.send("🔄 **Relace vlákna byla resetována.** Další zpráva v tomto vlákně začne novou session.")
    else:
        await ctx.send("ℹ️ Toto vlákno nemá žádnou aktivní navázanou session.")


@bot.command(name="quota", aliases=["usage"])
async def cmd_quota(ctx: commands.Context):
    """Zobrazí aktuální stav kvót a limitů z Google Antigravity (5h a týdenní limit)."""
    if not is_authorized(ctx.author):
        return

    quota_groups = await asyncio.to_thread(get_agy_quota)
    if quota_groups:
        embed = format_quota_embed(quota_groups, discord_module=discord)
        await ctx.send(embed=embed)
    else:
        await ctx.send(
            "⚠️ Nepodařilo se načíst živé kvóty z Google Antigravity (`agy`). "
            "Ujisti se, že je CLI `agy` nainstalováno a přihlášeno k účtu."
        )


@bot.command(name="limits")
async def cmd_limits(ctx: commands.Context):
    if not is_authorized(ctx.author):
        return

    # 1. Pokud máme k dispozici živá data o kvótách z agy, pošleme nejdříve přehled kvót
    try:
        quota_groups = await asyncio.to_thread(get_agy_quota)
        if quota_groups:
            quota_embed = format_quota_embed(quota_groups, discord_module=discord)
            await ctx.send(embed=quota_embed)
    except Exception:
        pass

    # 2. Obecný přehled rychlostních limitů (RPM, TPM, RPD)
    embed = discord.Embed(
        title="📊 Přehled limitů modelů a providerů",
        description="Rychlosti a kvóty pro jednotlivé AI modely a agenty:",
        color=discord.Color.blue()
    )

    for m_id, m_data in MODEL_LIMITS.items():
        is_current = " (AKTIVNÍ)" if os.environ.get("GEMINI_MODEL", DEFAULT_GEMINI_MODEL) == m_id else ""
        embed.add_field(
            name=f"🔹 {m_data['name']}{is_current}",
            value=(
                f"• **Free Tier:** {m_data['tier_free']}\n"
                f"• **Pay-As-You-Go:** {m_data['tier_paid']}\n"
                f"• *{m_data['desc']}*"
            ),
            inline=False
        )

    for prov_id, prov_text in PROVIDER_LIMITS.items():
        if prov_id != "agy":
            is_current = " (AKTIVNÍ)" if CONFIG.agent_provider == prov_id else ""
            embed.add_field(
                name=f"🛠️ Provider: `{prov_id}`{is_current}",
                value=prov_text,
                inline=False
            )

    embed.set_footer(text="RPM = požadavky/min • TPM = tokeny/min • RPD = požadavky/den • Pro živý stav použij !quota")
    await ctx.send(embed=embed)


@bot.command(name="previews")
async def cmd_previews(ctx: commands.Context):
    if not is_authorized(ctx.author):
        return
    await ctx.send(f"```\n{list_previews()}\n```")


@bot.command(name="stop_preview")
async def cmd_stop_preview(ctx: commands.Context, name: str):
    if not is_authorized(ctx.author):
        return
    await ctx.send(stop_preview(name))


@bot.command(name="remote")
async def cmd_remote(ctx: commands.Context, action: str | None = None):
    """Správa persistentního Google Antigravity Remote Control daemonu."""
    if not is_authorized(ctx.author):
        return

    action = (action or "status").lower().strip()
    if action == "status":
        info = await asyncio.to_thread(get_remote_control_status)
        is_active = info.get("active", False)
        instance_name = info.get("instance_name") or CONFIG.remote_control_name
        pid = info.get("pid")
        url = info.get("url", "https://antigravity.google.com")

        color = discord.Color.green() if is_active else discord.Color.red()
        status_text = "🟢 **Aktivní** (běží 24/7 na pozadí)" if is_active else "🔴 **Neaktivní** (zastaveno)"

        embed = discord.Embed(
            title="📡 Antigravity Remote Control",
            description=f"Stav: {status_text}",
            color=color,
        )
        embed.add_field(name="🏷️ Instance", value=f"`{instance_name}`", inline=True)
        if pid:
            embed.add_field(name="⚙️ PID", value=f"`{pid}`", inline=True)
        embed.add_field(name="🌐 Webové rozhraní", value=f"[Otevřít na antigravity.google.com]({url})", inline=False)
        embed.set_footer(text="Příkazy: !remote status • !remote restart • !remote start • !remote stop")
        await ctx.send(embed=embed)

    elif action in ("start", "restart"):
        await ctx.send(f"🔄 {'Restartuji' if action == 'restart' else 'Spouštím'} Remote Control daemon...")
        fn = restart_remote_control if action == "restart" else start_remote_control
        success, msg = await asyncio.to_thread(fn, CONFIG.remote_control_name)
        if success:
            info = await asyncio.to_thread(get_remote_control_status)
            inst = info.get("instance_name") or CONFIG.remote_control_name
            await ctx.send(
                f"✅ Remote Control daemon byl úspěšně spuštěn (instance: `{inst}`).\n"
                f"🌐 Dostupný na https://antigravity.google.com"
            )
        else:
            await ctx.send(f"❌ Chyba při spouštění Remote Control:\n```\n{msg}\n```")

    elif action == "stop":
        await ctx.send("🛑 Zastavuji Remote Control daemon...")
        success, msg = await asyncio.to_thread(stop_remote_control)
        if success:
            await ctx.send("✅ Remote Control daemon byl zastaven.")
        else:
            await ctx.send(f"❌ Chyba při zastavování:\n```\n{msg}\n```")

    else:
        await ctx.send("Neznámá akce. Použij: `!remote status`, `!remote restart`, `!remote start`, nebo `!remote stop`.")


@bot.event
async def on_message(message: discord.Message):
    if message.author.bot or not is_authorized(message.author):
        return

    # Zpracování příkazů začínajících vykřičníkem (!repos, !clone, !model, ...)
    if message.content.startswith("!"):
        await bot.process_commands(message)
        return

    text = message.content.strip()
    if not text:
        return

    is_thread = isinstance(message.channel, discord.Thread)

    # Pokud uživatel ve vlákně selhaného úkolu pošle přímo přesný klíč modelu
    clean_text = text.strip().strip("\"'")
    if is_thread and message.channel.id in FAILED_TASKS and clean_text in AVAILABLE_MODELS:
        os.environ["GEMINI_MODEL"] = clean_text
        failed_data = FAILED_TASKS.pop(message.channel.id)
        repo_path, target_repo, prompt, user_id = failed_data[0], failed_data[1], failed_data[2], failed_data[3]
        session_id = failed_data[4] if len(failed_data) > 4 else None
        existing_branch = failed_data[5] if len(failed_data) > 5 else None

        await message.channel.send(
            f"✅ Model nastaven na: `{clean_text}`.\n"
            f"🚀 **Opakuji původní úkol:** *{prompt}*"
        )
        await run_agent_workflow(
            thread=message.channel,
            repo_path=repo_path,
            target_repo=target_repo,
            prompt=prompt,
            user_id=user_id,
            session_id=session_id,
            existing_branch=existing_branch,
        )
        return

    # Určení cílového repozitáře a existující session
    repos = [d.name for d in CONFIG.repos_dir.iterdir() if d.is_dir() and not d.name.startswith(".")]

    target_repo = None
    existing_session: ThreadSession | None = None

    if is_thread:
        existing_session = THREAD_SESSIONS.get(message.channel.id)
        if existing_session and existing_session.target_repo in repos:
            target_repo = existing_session.target_repo

        if not target_repo:
            parent_name = getattr(message.channel.parent, "name", "").lower()
            target_repo = next((r for r in repos if r.lower() == parent_name), None)

    if not target_repo:
        channel_name = getattr(message.channel, "name", "").lower()
        target_repo = next((r for r in repos if r.lower() == channel_name), None)

    if not target_repo:
        target_repo = next((r for r in repos if r.lower() in text.lower()), None)

    if not target_repo:
        await message.reply(
            f"Nevím, o který repozitář jde. Napiš zprávu do kanálu pojmenovaného podle repa (např. `#house`) "
            f"nebo zmiň jeho název ve zprávě. Dostupné: {', '.join(f'`{r}`' for r in repos) or 'žádné'}."
        )
        return

    repo_path = CONFIG.repos_dir / target_repo

    if is_thread:
        thread = message.channel
        session_id = existing_session.session_id if existing_session else None
        existing_branch = existing_session.branch if existing_session else None
    else:
        # Vytvoříme vlákno (Thread) pro přehlednost průběhu úkolu - nový příspěvek = nová session
        thread = await message.create_thread(name=f"mipilot: {text[:70]}")
        session_id = None
        existing_branch = None

    await run_agent_workflow(
        thread=thread,
        repo_path=repo_path,
        target_repo=target_repo,
        prompt=text,
        user_id=message.author.id,
        session_id=session_id,
        existing_branch=existing_branch,
    )


def main():
    try:
        ensure_remote_control(CONFIG.remote_control_name)
    except Exception as e:
        print(f"[RemoteControl] Chyba při počátečním spuštění daemonu: {e}")
    bot.run(CONFIG.discord_token)


if __name__ == "__main__":
    main()
