#!/usr/bin/env python3
"""
Interactive AI Agent for AT Chat Mask.
Dynamically generates CSV from chat files and creates AskTable demo cases.
"""

import time
from pathlib import Path
from typing import Optional

from asktable import Asktable
from rich.markdown import Markdown
from rich.panel import Panel

from .config import ChatMaskSettings
from .csv_generator import CSVGenerator
from .resource_manager import ResourceManager
from .models import CaseInfo
from .utils import console, extract_key_error, get_error_suggestion, setup_logging, get_logger

# Initialize logger
logger = get_logger(__name__)


class ChatMaskAgent:
    """Interactive agent for creating AskTable demo cases from chat files."""

    def __init__(
        self,
        settings: Optional[ChatMaskSettings] = None,
        api_key: Optional[str] = None,
        api_base: Optional[str] = None,
    ):
        """
        Initialize the agent.

        Args:
            settings: Configuration settings (if None, loads from env)
            api_key: AskTable API key (overrides settings)
            api_base: AskTable API base URL (overrides settings)
        """
        # Load settings
        if settings is None:
            try:
                settings = ChatMaskSettings()
            except Exception as e:
                console.print(
                    f"[red]❌ 配置错误[/red]: {extract_key_error(e)}\n"
                    f"[yellow]💡 提示[/yellow]: 请在 .env 文件中设置 ASKTABLE_API_KEY"
                )
                raise

        self.settings = settings

        # Override with explicit parameters
        if api_key:
            self.settings.asktable_api_key = api_key
        if api_base:
            self.settings.asktable_api_base = api_base

        # Initialize AskTable client
        self.client = Asktable(
            base_url=self.settings.asktable_api_base,
            api_key=self.settings.asktable_api_key,
        )

        # 准备 LLM 配置
        llm_config = {
            "base_url": self.settings.llm_base_url,
            "api_key": self.settings.llm_api_key,
            "sql_model": self.settings.llm_sql_model,
            "data_gen_model": self.settings.llm_data_gen_model,
        }

        self.csv_generator = CSVGenerator(llm_config=llm_config)
        self.resource_manager = ResourceManager(self.client)

        # 立即获取并缓存 project_id
        self.project_id = self._fetch_project_id()

        # Case information (使用值对象)
        self.case: Optional[CaseInfo] = None

        logger.info("ChatMaskAgent initialized")

    def _fetch_project_id(self) -> Optional[str]:
        """初始化时获取 project_id

        Returns:
            Project ID 或 None
        """
        try:
            project = self.client.user.projects.retrieve_my_project()
            logger.info(f"Retrieved project ID: {project.id}")
            return project.id
        except Exception as e:
            logger.warning(f"Failed to retrieve project ID: {e}")
            return None

    def print_welcome(self):
        """Print a formatted welcome message."""
        welcome_text = """
# AT Chat Mask

从真实对话创建演示案例，使用虚拟数据保护客户隐私。

## 功能
- 📁 分析 chat-{编号}.json 文件
- 🔄 生成虚拟 CSV 数据
- 🤖 创建 AskTable Bot
- 💬 配置示例问题
- 🌐 生成公开分享链接

## 使用流程
1. 输入案例编号
2. 按提示输入案例信息
3. 确认并创建资源
4. 获取分享链接
"""
        panel = Panel(
            Markdown(welcome_text),
            title="[bold cyan]欢迎使用 AT Chat Mask[/bold cyan]",
            border_style="cyan",
        )
        console.print(panel)

    def print_header(self, text: str):
        """Print a formatted header."""
        console.print(f"\n[bold cyan]{'=' * 70}[/bold cyan]")
        console.print(f"[bold]{text}[/bold]")
        console.print(f"[bold cyan]{'=' * 70}[/bold cyan]")

    def print_step(self, step_num: int, text: str):
        """Print a step message."""
        console.print(f"\n[bold cyan]{step_num}.[/bold cyan] [bold]{text}[/bold]")

    def ask_user(self, question: str, default: Optional[str] = None) -> str:
        """Ask user a question and return the answer."""
        if default:
            prompt = f"[cyan]{question}[/cyan] [dim]\\[{default}][/dim]: "
        else:
            prompt = f"[cyan]{question}[/cyan]: "

        console.print(prompt, end="")
        answer = input().strip()
        return answer if answer else default

    def ask_yes_no(self, question: str, default: bool = True) -> bool:
        """Ask a yes/no question."""
        default_str = "Y/n" if default else "y/N"
        console.print(f"[cyan]{question}[/cyan] [dim]\\[{default_str}][/dim]: ", end="")
        answer = input().strip().lower()

        if not answer:
            return default
        return answer in ["y", "yes", "是", "对"]

    def collect_case_info(self) -> bool:
        """Collect case information from user."""
        self.print_welcome()

        # Ask for case number
        console.print("\n[bold]📁 请输入案例编号[/bold]")
        console.print("[dim]案例编号格式：001, 002, 003 等[/dim]")
        console.print("[dim]系统将自动查找对应的 chat-{编号}.json 文件[/dim]")

    def _load_case_file(self) -> bool:
        """加载案例文件"""
        console.print("\n[bold]📁 请输入案例编号[/bold]")
        console.print("[dim]案例编号格式：001, 002, 003 等[/dim]")
        console.print("[dim]系统将自动查找对应的 chat-{编号}.json 文件[/dim]")

        case_number = self.ask_user("案例编号", default="001")

        if not case_number.isdigit():
            console.print(f"\n[red]❌ 错误[/red]: 案例编号必须是数字（如：001, 002）")
            logger.error(f"Invalid case number format: {case_number}")
            return False

        chat_filename = f"chat-{case_number}.json"
        chat_file = Path.cwd() / chat_filename

        if not chat_file.exists():
            console.print(f"\n[red]❌ 错误[/red]: 找不到文件 '{chat_filename}'")
            console.print(f"[yellow]💡 提示[/yellow]: 请确保文件名格式为 chat-{case_number}.json")
            logger.error(f"File not found: {chat_filename}")
            return False

        # 创建 CaseInfo 对象
        self.case = CaseInfo.from_case_number(case_number, chat_file)

        console.print(f"[green]✓[/green] 找到文件: [dim]{chat_file}[/dim]")
        console.print(f"[green]✓[/green] 案例 ID: [cyan]{self.case.case_id}[/cyan]")
        logger.info(f"Case ID: {self.case.case_id}")
        return True

        # Analyze chat file to extract structure and generate case name
        console.print(f"\n[cyan]🔍 分析对话文件...[/cyan]")
        try:
            with console.status("[cyan]分析中...[/cyan]"):
                analysis = self.csv_generator.analyze_messages(self.chat_file)

            console.print(f"[green]✓[/green] 发现 [bold]{len(analysis['fields'])}[/bold] 个数据字段")
            console.print(f"[green]✓[/green] 发现 [bold]{len(analysis['sql_queries'])}[/bold] 个查询")
            logger.info(
                f"Analysis complete: {len(analysis['fields'])} fields, "
                f"{len(analysis['sql_queries'])} queries"
            )

            # Auto-generate case name from analysis
            generated_name = self._generate_case_name(analysis)
            console.print(f"\n[bold]📝 自动生成案例名称[/bold]")
            console.print(f"[green]✓[/green] 案例名称: [cyan]{generated_name}[/cyan]")

            # Allow user to modify if needed
            if self.ask_yes_no("是否使用此名称？", default=True):
                self.case_name = generated_name
            else:
                console.print("[dim]请输入自定义名称：[/dim]")
                self.case_name = self.ask_user("案例名称", default=generated_name)

            logger.info(f"Case name: {self.case_name}")

            # Extract questions from messages
            self._extract_questions_from_messages()

        except Exception as e:
            key_error = extract_key_error(e)
            console.print(f"[red]⚠️  分析失败[/red]: {key_error}")
            logger.error(f"Analysis failed: {e}", exc_info=True)
            return False

        # Ask user to select questions
        console.print(f"\n[bold]💬 预设问题[/bold]")
        if self.sample_questions:
            console.print(f"从 Chat 中提取到 [bold]{len(self.sample_questions)}[/bold] 个问题：")
            for i, q in enumerate(self.sample_questions, 1):
                console.print(f"  [dim]{i}.[/dim] {q}")

            # Let user select 2-3 questions
            self._select_questions()
        else:
            console.print("[yellow]未找到问题，请手动输入：[/yellow]")
            self._collect_additional_questions()

        return True

    def _generate_case_name(self, analysis: dict) -> str:
        """从分析结果生成案例名称

        Args:
            analysis: 分析结果

        Returns:
            中文案例名称
        """
        # 优先使用 LLM 生成
        if self.csv_generator.llm_planner:
            try:
                return self.csv_generator.llm_planner.generate_case_name(analysis)
            except Exception as e:
                logger.warning(f"LLM case name generation failed: {e}")

        # 降级到通用名称
        field_count = len(analysis.get('fields', []))
        return f"数据分析案例（{field_count}个字段）"

    def _extract_questions_from_messages(self):
        """Extract questions from messages.json."""
        try:
            import json

            with open(self.chat_file, "r", encoding="utf-8") as f:
                data = json.load(f)

            items = data.get("items", [])
            for item in items:
                if item.get("role") == "human":
                    content = item.get("content", {})
                    text = content.get("text", "").strip()
                    if text and text not in self.sample_questions:
                        self.sample_questions.append(text)

            logger.info(f"Extracted {len(self.sample_questions)} questions from messages")

        except Exception as e:
            console.print(f"[yellow]⚠️  提取问题失败[/yellow]: {extract_key_error(e)}")
            logger.warning(f"Failed to extract questions: {e}", exc_info=True)

    def _select_questions(self):
        """Let user select 2-3 questions from extracted questions."""
        console.print("\n[cyan]请从上述问题中选择 2-3 个作为预设问题[/cyan]")
        console.print("[dim]输入问题编号，用空格或逗号分隔（例如：1 3 5 或 1,3,5）[/dim]")
        console.print("[dim]直接回车使用所有问题[/dim]")

        console.print("\n[cyan]选择问题编号[/cyan]: ", end="")
        selection = input().strip()

        if not selection:
            # Use all questions
            console.print(f"[green]✓[/green] 将使用所有 {len(self.sample_questions)} 个问题")
            logger.info(f"Using all {len(self.sample_questions)} questions")
            return

        # Parse selection
        try:
            # Replace commas with spaces and split
            selection = selection.replace(',', ' ')
            indices = [int(x.strip()) for x in selection.split() if x.strip()]

            # Validate indices
            valid_indices = []
            for idx in indices:
                if 1 <= idx <= len(self.sample_questions):
                    valid_indices.append(idx)
                else:
                    console.print(f"[yellow]⚠[/yellow] 忽略无效编号: {idx}")

            if not valid_indices:
                console.print("[yellow]⚠[/yellow] 未选择有效问题，将使用所有问题")
                logger.warning("No valid questions selected, using all")
                return

            # Keep only selected questions
            selected_questions = [self.sample_questions[i-1] for i in valid_indices]
            self.sample_questions = selected_questions

            console.print(f"[green]✓[/green] 已选择 {len(selected_questions)} 个问题：")
            for i, q in enumerate(selected_questions, 1):
                console.print(f"  [dim]{i}.[/dim] {q}")

            logger.info(f"Selected {len(selected_questions)} questions: {valid_indices}")

        except ValueError as e:
            console.print(f"[yellow]⚠[/yellow] 输入格式错误，将使用所有问题")
            logger.warning(f"Invalid selection format: {e}")

        # Ask if user wants to add more questions
        if self.ask_yes_no("\n是否添加更多问题？", default=False):
            self._collect_additional_questions()

    def _collect_additional_questions(self):
        """Collect additional questions from user."""
        console.print("\n[dim]请输入额外的问题（每行一个，输入空行结束）：[/dim]")

        while True:
            console.print(f"[cyan]问题 {len(self.sample_questions) + 1}[/cyan]: ", end="")
            question = input().strip()
            if not question:
                break
            self.sample_questions.append(question)
            logger.debug(f"Added question: {question}")

    def confirm_creation(self) -> bool:
        """Confirm case creation with user."""
        self.print_header("确认案例信息")

        console.print(f"\n[bold]📋 案例信息:[/bold]")
        console.print(f"  • 案例编号: [cyan]{self.case_id}[/cyan]")
        console.print(f"  • 案例名称: [cyan]{self.case_name}[/cyan]")
        console.print(f"  • Chat 文件: [dim]{self.chat_file}[/dim]")
        console.print(f"  • 预设问题数量: [cyan]{len(self.sample_questions)}[/cyan]")

        if self.sample_questions:
            console.print(f"\n[bold]💬 预设问题:[/bold]")
            for i, q in enumerate(self.sample_questions[:5], 1):
                console.print(f"  [dim]{i}.[/dim] {q}")
            if len(self.sample_questions) > 5:
                console.print(f"  [dim]... 还有 {len(self.sample_questions) - 5} 个问题[/dim]")

        console.print(f"\n[bold]🚀 将创建以下资源:[/bold]")
        console.print(f"  • Datasource: [cyan]{self.case_id}[/cyan] ([dim]{self.case_name}[/dim])")
        console.print(f"  • Bot: [cyan]{self.case_id}[/cyan] ([dim]{self.case_name}[/dim]) [green]\\[公开分享][/green]")
        console.print(f"  • Chat: [cyan]{self.case_id}[/cyan] ([dim]{self.case_name}[/dim])")

        return self.ask_yes_no("\n确认创建？", default=True)

    def generate_csv(self, num_rows: Optional[int] = None) -> bool:
        """Generate CSV from messages.json."""
        if num_rows is None:
            num_rows = self.settings.default_num_rows

        self.print_step(1, "生成虚拟数据 CSV 文件...")

        try:
            # Analyze messages first
            with console.status(f"[cyan]分析对话内容...[/cyan]"):
                analysis = self.csv_generator.analyze_messages(self.chat_file)

            # Create output directory (same name as chat file)
            output_dir = self.chat_file.parent / self.chat_file.stem
            output_dir.mkdir(parents=True, exist_ok=True)
            console.print(f"[green]✓[/green] 输出目录：[dim]{output_dir}[/dim]")

            # Generate multiple CSVs and save to output directory
            with console.status(f"[cyan]生成 {num_rows} 行数据...[/cyan]"):
                csv_files = self.csv_generator.generate_multiple_csvs_from_analysis(
                    analysis=analysis,
                    num_rows=num_rows,
                    output_dir=output_dir,
                )

            # Collect generated file paths
            self.csv_files = [csv_file for _, csv_file in csv_files]

            if len(self.csv_files) == 1:
                console.print(f"[green]✓[/green] CSV 文件已生成：[dim]{self.csv_files[0].name}[/dim]")
            else:
                console.print(f"[green]✓[/green] 共生成 {len(self.csv_files)} 个数据表:")
                for csv_file in self.csv_files:
                    console.print(f"    - [dim]{csv_file.name}[/dim]")

            return True

        except Exception as e:
            key_error = extract_key_error(e)
            console.print(f"[red]❌ 生成 CSV 失败[/red]: {key_error}")
            suggestion = get_error_suggestion(e)
            console.print(f"[yellow]💡 建议[/yellow]: {suggestion}")
            logger.error(f"CSV generation failed: {e}", exc_info=True)
            return False

    def create_datasource(self) -> Optional[str]:
        """Create datasource and upload CSV file."""
        self.print_step(2, "创建数据源...")

        try:
            datasource_name = f"{self.case_id} - {self.case_name}"

            # 清理同名数据源
            self.resource_manager.cleanup_datasource(datasource_name)

            # Create datasource with descriptive name
            with console.status("[cyan]创建数据源...[/cyan]"):
                datasource = self.client.datasources.create(
                    engine="excel",
                    name=datasource_name,
                )

            ds_id = datasource.id
            console.print(f"[green]✓[/green] 数据源已创建: [cyan]{ds_id}[/cyan]")
            console.print(f"  名称: [dim]{self.case_id} - {self.case_name}[/dim]")
            logger.info(f"Datasource created: {ds_id}")

            # Upload all CSV files
            console.print(f"  [cyan]上传 CSV 文件...[/cyan]")
            for csv_file in self.csv_files:
                with console.status(f"[cyan]上传 {csv_file.name}...[/cyan]"):
                    with open(csv_file, "rb") as f:
                        self.client.datasources.add_file(
                            datasource_id=ds_id,
                            file=f,
                        )
                console.print(f"  [green]✓[/green] {csv_file.name} 已上传")
                logger.info(f"CSV uploaded to datasource {ds_id}: {csv_file.name}")

            if len(self.csv_files) > 1:
                console.print(f"[green]✓[/green] 共上传 {len(self.csv_files)} 个文件")

            # Trigger metadata processing
            console.print(f"  [cyan]处理元数据...[/cyan]")
            with console.status("[cyan]处理中...[/cyan]"):
                self.client.datasources.meta.create(datasource_id=ds_id)

            console.print(f"[green]✓[/green] 元数据处理已触发")
            logger.info(f"Metadata processing triggered for datasource {ds_id}")

            # Print datasource URL
            if self.project_id:
                ds_url = f"https://cloud.asktable.com/u/p/{self.project_id}/data/ds/{ds_id}/meta"
                console.print(f"  [cyan]数据源链接:[/cyan] [link={ds_url}]{ds_url}[/link]")
                logger.info(f"Datasource URL: {ds_url}")

            return ds_id

        except Exception as e:
            key_error = extract_key_error(e)
            console.print(f"[red]❌ 创建数据源失败[/red]: {key_error}")
            suggestion = get_error_suggestion(e)
            console.print(f"[yellow]💡 建议[/yellow]: {suggestion}")
            logger.error(f"Datasource creation failed: {e}", exc_info=True)
            return None

    def create_bot(self, ds_id: str) -> Optional[str]:
        """Create bot with sample questions."""
        self.print_step(3, "创建机器人...")

        try:
            bot_name = f"{self.case_id} - {self.case_name}"

            # 清理同名机器人
            self.resource_manager.cleanup_bot(bot_name)

            # Limit questions to configured maximum
            max_questions = self.settings.max_sample_questions
            questions = self.sample_questions[:max_questions]

            with console.status("[cyan]创建机器人...[/cyan]"):
                bot = self.client.bots.create(
                    name=bot_name,
                    datasource_ids=[ds_id],
                    sample_questions=questions,
                    publish=True,
                )

            bot_id = bot.id
            console.print(f"[green]✓[/green] 机器人已创建: [cyan]{bot_id}[/cyan]")
            console.print(f"  名称: [dim]{self.case_id} - {self.case_name}[/dim]")
            console.print(f"[green]✓[/green] 已开启公开分享")

            # Generate share URL with project ID
            if self.project_id:
                share_url = f"https://cloud.asktable.com/u/p/{self.project_id}/talk/bot/{bot_id}/share"
            else:
                # Fallback to simple URL if project ID not available
                share_url = f"https://cloud.asktable.com/bots/{bot_id}"
            console.print(f"[green]✓[/green] 分享链接: [link={share_url}]{share_url}[/link]")
            logger.info(f"Bot created: {bot_id}, share URL: {share_url}")

            return bot_id

        except Exception as e:
            key_error = extract_key_error(e)
            console.print(f"[red]❌ 创建机器人失败[/red]: {key_error}")
            suggestion = get_error_suggestion(e)
            console.print(f"[yellow]💡 建议[/yellow]: {suggestion}")
            logger.error(f"Bot creation failed: {e}", exc_info=True)
            return None

    def create_chat(self, bot_id: str) -> Optional[str]:
        """Create chat."""
        self.print_step(4, "创建对话...")

        try:
            # Use datasource name for chat (same as datasource and bot)
            chat_name = f"{self.case_id} - {self.case_name}"

            # 清理同名对话
            self.resource_manager.cleanup_chat(chat_name)

            with console.status("[cyan]创建对话...[/cyan]"):
                chat = self.client.chats.create(
                    bot_id=bot_id,
                    name=chat_name,
                )

            chat_id = chat.id
            console.print(f"[green]✓[/green] 对话已创建: [cyan]{chat_id}[/cyan]")
            console.print(f"  名称: [dim]{self.case_id} - {self.case_name}[/dim]")

            # Generate chat URL with project ID
            if self.project_id:
                chat_url = f"https://cloud.asktable.com/u/p/{self.project_id}/talk/chat/{chat_id}/bot/{bot_id}"
            else:
                # Fallback to simple URL if project ID not available
                chat_url = f"https://cloud.asktable.com/chats/{chat_id}"
            console.print(f"[green]✓[/green] 对话链接: [link={chat_url}]{chat_url}[/link]")
            logger.info(f"Chat created: {chat_id}, URL: {chat_url}")

            return chat_id

        except Exception as e:
            key_error = extract_key_error(e)
            console.print(f"[red]❌ 创建对话失败[/red]: {key_error}")
            suggestion = get_error_suggestion(e)
            console.print(f"[yellow]💡 建议[/yellow]: {suggestion}")
            logger.error(f"Chat creation failed: {e}", exc_info=True)
            return None

    def _check_datasource_ready(self, ds) -> tuple[Optional[bool], str]:
        """检查数据源是否就绪

        Args:
            ds: 数据源对象

        Returns:
            (is_ready, status_message)
            - is_ready: True=就绪, False=失败, None=处理中
            - status_message: 状态描述
        """
        # 优先级1: meta_status（主要指标）
        if hasattr(ds, 'meta_status'):
            if ds.meta_status == 'success':
                return True, "元数据处理完成"
            if ds.meta_status == 'failed':
                return False, "元数据处理失败"
            return None, f"处理中: {ds.meta_status}"

        # 优先级2: table_count
        if hasattr(ds, 'table_count') and ds.table_count > 0:
            return True, f"已就绪 ({ds.table_count} 个表)"

        # 优先级3: 旧版 status 字段
        if hasattr(ds, 'status') and ds.status in ['ready', 'active', 'success']:
            return True, f"已就绪 (状态: {ds.status})"

        return None, "等待中"

    def wait_for_datasource(self, ds_id: str, max_wait: Optional[int] = None) -> bool:
        """Wait for datasource metadata to be ready."""
        if max_wait is None:
            max_wait = self.settings.datasource_wait_timeout

        self.print_step(5, "等待数据源处理完成...")

        console.print(f"  [dim]数据源需要一些时间来处理元数据...[/dim]")
        console.print(f"  [dim]最多等待 {max_wait} 秒...[/dim]")

        interval = self.settings.datasource_wait_interval
        elapsed = 0

        while elapsed < max_wait:
            try:
                ds = self.client.datasources.retrieve(datasource_id=ds_id)
                is_ready, message = self._check_datasource_ready(ds)

                if is_ready is True:
                    console.print(f"[green]✓[/green] 数据源{message}")
                    logger.info(f"Datasource {ds_id} ready: {message}")
                    return True
                elif is_ready is False:
                    console.print(f"[red]✗[/red] 数据源{message}")
                    logger.error(f"Datasource {ds_id} failed: {message}")
                    return False
                else:
                    if elapsed % 10 == 0:
                        console.print(f"  [dim]{message}[/dim]")

            except Exception as e:
                if elapsed % 10 == 0:
                    logger.debug(f"Waiting for datasource: {e}")

            time.sleep(interval)
            elapsed += interval

            if elapsed < max_wait and elapsed % 10 == 0:
                console.print(f"  [dim]等待中... ({elapsed}s)[/dim]")

        console.print("[yellow]⚠️  等待超时，但数据源可能仍在处理中[/yellow]")
        console.print("  [dim]将继续尝试发送测试问题...[/dim]")
        logger.warning(f"Datasource {ds_id} wait timeout after {max_wait}s")
        return False

    def send_test_questions(self, chat_id: str):
        """Send test questions to chat."""
        self.print_step(6, "发送测试问题...")

        # Only send first 2 questions
        test_questions = self.sample_questions[:2]

        for i, question in enumerate(test_questions, 1):
            console.print(f"\n  [cyan]问题 {i}[/cyan]: {question}")

            # Retry logic for datasource not ready
            max_retries = 3
            retry_delay = 5  # seconds

            for attempt in range(max_retries):
                try:
                    with console.status("[cyan]发送中...[/cyan]"):
                        response = self.client.chats.messages.create(
                            chat_id=chat_id,
                            question=question,
                        )

                    console.print("  [green]✓[/green] 已发送")
                    logger.info(f"Test question sent: {question}")

                    if hasattr(response, "answer") and response.answer:
                        preview = (
                            response.answer[:100] + "..."
                            if len(response.answer) > 100
                            else response.answer
                        )
                        console.print(f"  [dim]回答预览: {preview}[/dim]")

                    # Success, break retry loop
                    break

                except Exception as e:
                    error_msg = str(e)
                    if "DATASOURCE_META_NOT_READY" in error_msg:
                        if attempt < max_retries - 1:
                            console.print(f"  [yellow]⚠[/yellow] 数据源尚未就绪，{retry_delay}秒后重试... (尝试 {attempt + 1}/{max_retries})")
                            logger.warning(f"Datasource not ready, retrying in {retry_delay}s (attempt {attempt + 1}/{max_retries})")
                            time.sleep(retry_delay)
                        else:
                            console.print("  [yellow]⚠️  数据源尚未就绪，已达到最大重试次数[/yellow]")
                            logger.warning(f"Datasource not ready after {max_retries} attempts for question: {question}")
                    else:
                        key_error = extract_key_error(e)
                        console.print(f"  [red]❌ 发送失败[/red]: {key_error}")
                        logger.error(f"Failed to send test question: {e}", exc_info=True)
                        break  # Don't retry for other errors

    def print_summary(self, ds_id: str, bot_id: str, chat_id: str):
        """Print summary of created resources."""
        self.print_header("✅ 创建完成！")

        console.print("\n[bold]📋 案例信息:[/bold]")
        console.print(f"  • 案例编号: [cyan]{self.case_id}[/cyan]")
        console.print(f"  • 案例名称: [cyan]{self.case_name}[/cyan]")

        console.print("\n[bold]📊 生成的数据表:[/bold]")
        for csv_file in self.csv_files:
            console.print(f"  • {csv_file.name}")

        console.print("\n[bold]🔗 创建的资源:[/bold]")
        console.print(f"  • Datasource ID: [cyan]{ds_id}[/cyan]")
        console.print(f"  • Bot ID: [cyan]{bot_id}[/cyan]")
        console.print(f"  • Chat ID: [cyan]{chat_id}[/cyan]")

        console.print("\n[bold]🌐 访问链接:[/bold]")
        # Generate URLs with project ID
        if self.project_id:
            ds_url = f"https://cloud.asktable.com/u/p/{self.project_id}/data/ds/{ds_id}/meta"
            bot_url = f"https://cloud.asktable.com/u/p/{self.project_id}/talk/bot/{bot_id}/share"
            chat_url = f"https://cloud.asktable.com/u/p/{self.project_id}/talk/chat/{chat_id}/bot/{bot_id}"
        else:
            # Fallback to simple URLs if project ID not available
            ds_url = f"https://cloud.asktable.com/datasources/{ds_id}"
            bot_url = f"https://cloud.asktable.com/bots/{bot_id}"
            chat_url = f"https://cloud.asktable.com/chats/{chat_id}"
        console.print(f"  • Datasource 链接: [link={ds_url}]{ds_url}[/link]")
        console.print(f"  • Bot 分享链接: [link={bot_url}]{bot_url}[/link]")
        console.print(f"  • Chat 链接: [link={chat_url}]{chat_url}[/link]")

        console.print(f"\n[green]✓[/green] 所有资源使用统一的标识: [cyan]'{self.case_id}'[/cyan]")
        console.print(f"[green]✓[/green] Bot 已开启公开分享，可以分享给任何人")
        console.print(
            f"[green]✓[/green] Bot 中已预配置 [cyan]{len(self.sample_questions)}[/cyan] 个示例问题"
        )

        console.print("\n[bold]💡 提示:[/bold]")
        console.print("  • 您现在可以在 AskTable Web 界面中测试 Bot 和 Chat")
        console.print("  • 如果数据源尚未就绪，请等待几分钟后再试")
        if len(self.csv_files) == 1:
            console.print(f"  • CSV 文件已保存在: [dim]{self.csv_files[0]}[/dim]")
        else:
            console.print("  • CSV 文件已保存在当前目录")

        logger.info(f"Case creation complete: {self.case_id}")

    def run(self):
        """Run the agent."""
        try:
            # Collect case information
            if not self.collect_case_info():
                console.print("\n[yellow]❌ 已取消[/yellow]")
                return

            # Confirm creation
            if not self.confirm_creation():
                console.print("\n[yellow]❌ 已取消[/yellow]")
                return

            # Create resources
            self.print_header("🚀 开始创建资源")

            # Step 1: Generate CSV
            if not self.generate_csv():
                return

            # Step 2: Create datasource
            ds_id = self.create_datasource()
            if not ds_id:
                return

            # Step 3: Create bot
            bot_id = self.create_bot(ds_id)
            if not bot_id:
                return

            # Step 4: Create chat
            chat_id = self.create_chat(bot_id)
            if not chat_id:
                return

            # Step 5: Automatically wait for datasource to be ready
            console.print("\n")
            self.wait_for_datasource(ds_id)

            # Step 6: Send test questions to chat
            self.send_test_questions(chat_id)

            # Print summary
            self.print_summary(ds_id, bot_id, chat_id)

        except KeyboardInterrupt:
            console.print("\n\n[yellow]⚠️  已中断[/yellow]")
            logger.info("User interrupted")
        except Exception as e:
            key_error = extract_key_error(e)
            console.print(f"\n\n[red]❌ 错误[/red]: {key_error}")
            suggestion = get_error_suggestion(e)
            console.print(f"[yellow]💡 建议[/yellow]: {suggestion}")
            logger.error(f"Unexpected error: {e}", exc_info=True)


def main():
    """Main entry point."""
    # Setup logging
    try:
        settings = ChatMaskSettings()
        setup_logging(log_level=settings.log_level, log_file=settings.log_file)
    except Exception:
        # If settings fail, use defaults
        setup_logging()

    logger.info("AT Chat Mask started")

    # Run agent
    agent = ChatMaskAgent()
    agent.run()

    logger.info("AT Chat Mask finished")


if __name__ == "__main__":
    main()
