import json, httpx, sys, time
from datetime import datetime
from pathlib import Path

from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.text import Text
from rich import box

console = Console()

SCENARIOS = {
    "science":    ("🔬 科学研究", "🔬"),
    "ai":         ("🤖 AI 对话", "🤖"),
    "ecommerce":  ("🛒 电商运营", "🛒"),
    "mechanical": ("⚙️ 机械工程", "⚙️"),
    "eda":        ("📊 数据分析", "📊"),
    "game":       ("🎮 游戏设计", "🎮"),
    "dev":        ("💻 软件开发", "💻"),
    "research":   ("📚 文献调研", "📚"),
}

def _load_config() -> dict:
    config_file = Path.home() / ".kogun" / "config.json"
    if not config_file.exists():
        return {}
    with open(config_file) as f:
        return json.load(f)

def _require_auth() -> dict:
    config = _load_config()
    if not config.get("token"):
        console.print("[bold red]❌ 未登录！请先运行 [cyan]kogun login[/][/]")
        sys.exit(1)
    return config

def _api_get(config: dict, path: str) -> dict:
    url = config.get("server_url", config.get("server", "https://www.kogun.site")).rstrip("/") + path
    headers = {"Authorization": f"Bearer {config['token']}"}
    try:
        resp = httpx.get(url, headers=headers, timeout=15)
        if resp.status_code == 401:
            console.print("[red]❌ Token 已过期，请重新 [cyan]kogun login[/][/]")
            sys.exit(1)
        return resp.json()
    except httpx.ConnectError:
        console.print(f"[red]❌ 无法连接到服务器: {url}[/]")
        return {}
    except Exception as e:
        console.print(f"[red]❌ 请求失败: {e}[/]")
        return {}

def _api_post(config: dict, path: str, data: dict = None) -> dict:
    url = config.get("server_url", config.get("server", "https://www.kogun.site")).rstrip("/") + path
    headers = {"Authorization": f"Bearer {config['token']}", "Content-Type": "application/json"}
    try:
        resp = httpx.post(url, headers=headers, json=data, timeout=15)
        if resp.status_code == 401:
            console.print("[red]❌ Token 已过期，请重新 [cyan]kogun login[/][/]")
            sys.exit(1)
        return resp.json()
    except httpx.ConnectError:
        console.print(f"[red]❌ 无法连接到服务器: {url}[/]")
        return {}
    except Exception as e:
        console.print(f"[red]❌ 请求失败: {e}[/]")
        return {}

# ========== Workshop 命令（替换旧版 Forge）==========

def cmd_forge_list(args):
    """查看我的算力任务"""
    config = _require_auth()
    data = _api_get(config, "/api/workshop/tasks")

    tasks = data if isinstance(data, list) else data.get("tasks", data.get("data", []))
    if not tasks:
        console.print("[yellow]📭 暂无算力任务[/]")
        console.print("   💡 前往 [bold]https://www.kogun.site/workshop[/] 提交任务")
        return

    table = Table(title=f"📋 超算工坊 · 任务列表 [dim](共 {len(tasks)} 条)[/]",
                  box=box.ROUNDED, header_style="bold cyan", border_style="blue")
    table.add_column("ID", style="dim", width=8)
    table.add_column("任务名称", min_width=20)
    table.add_column("状态", width=10)
    table.add_column("创建时间", width=16)

    for t in tasks:
        tid = str(t.get("id", "?"))
        name = (t.get("name") or t.get("title") or f"任务 #{tid}")[:30]
        status = t.get("status", "?")
        created = (t.get("created_at") or t.get("created") or "")[:16]
        table.add_row(tid, name, status, created)

    console.print(table)
    console.print("\n[dim]💡 详细管理请访问 https://www.kogun.site/workshop[/]")

def cmd_forge_new(args):
    """超算工坊需要前往网页端使用"""
    msg = """[bold yellow]⚠️ 超算工坊已迁移至网页端[/]

    💻 请打开浏览器访问:
    [bold cyan]https://www.kogun.site/workshop[/]

    支持的功能:
    • 上传代码/数据文件
    • 提交计算任务
    • 查看任务结果
    • 管理历史任务

    命令行支持查看任务列表: [bold]kogun forge list[/]"""
    console.print(Panel(msg, title="🏭 超算工坊", border_style="yellow"))

def cmd_forge_chat(args):
    cmd_forge_new(args)

def cmd_forge_search(args):
    cmd_forge_new(args)

def cmd_forge_share(args):
    cmd_forge_new(args)

def cmd_forge_summary(args):
    cmd_forge_new(args)

def cmd_forge_points(args):
    """查看积分余额"""
    config = _require_auth()
    data = _api_get(config, "/api/auth/me")
    credits = data.get("user", {}).get("credit_balance", data.get("credit_balance", 0))
    points = data.get("user", {}).get("points", data.get("points", 0))

    panel = Panel(
        f"[bold cyan]💰 余额: ¥{float(credits):.2f}[/]\n"
        f"[bold yellow]💎 积分: {int(points)}[/]",
        title="💳 账户信息",
        border_style="cyan",
        padding=(1, 2),
    )
    console.print(panel)

def cmd_forge_buy(args):
    """充值请前往网页端"""
    msg = """[bold yellow]⚠️ 充值功能需在网页端操作[/]

    💻 请打开浏览器访问:
    [bold cyan]https://www.kogun.site/finance[/]

    支持的充值方式:
    • 💳 微信支付
    • 💳 支付宝
    • 🏦 银行转账"""
    console.print(Panel(msg, title="💰 充值", border_style="yellow"))

def cmd_stats(args):
    """查看数据看板"""
    config = _require_auth()
    data = _api_get(config, "/api/user/stats")

    panel = Panel(
        f"[bold cyan]📊 数据看板[/]\n\n"
        f"  任务数: {data.get('task_count', data.get('total_tasks', 0))}\n"
        f"  节点数: {data.get('node_count', data.get('total_nodes', 0))}\n"
        f"  在线设备: {data.get('online_nodes', 0)}\n"
        f"  CO₂减排: {float(data.get('carbon_offset', data.get('carbon_offset_kg', 0))):.2f} kg",
        title="📈 我的数据",
        border_style="cyan",
    )
    console.print(panel)

def cmd_leaderboard(args):
    """查看排行榜"""
    config = _require_auth()
    limit = getattr(args, 'limit', 20)
    data = _api_get(config, f"/api/leaderboard?limit={limit}")

    entries = data if isinstance(data, list) else data.get("leaderboard", data.get("data", []))
    if not entries:
        console.print("[yellow]📭 暂无排行数据[/]")
        return

    table = Table(title=f"🏆 贡献排行 Top {limit}",
                  box=box.ROUNDED, header_style="bold cyan", border_style="cyan")
    table.add_column("#", width=4, style="dim")
    table.add_column("用户", min_width=16)
    table.add_column("算力得分", justify="right")
    table.add_column("收益", justify="right")
    table.add_column("在线", justify="right")

    for i, entry in enumerate(entries[:limit], 1):
        medal = "🥇" if i == 1 else "🥈" if i == 2 else "🥉" if i == 3 else str(i)
        username = entry.get("username", entry.get("user", f"用户#{entry.get('user_id','?')}"))
        score = str(entry.get("score", entry.get("compute_score", entry.get("total_score", "?"))))
        earnings = f"¥{float(entry.get('earnings', entry.get('total_earnings', 0))):.2f}"
        online = str(entry.get("online_hours", entry.get("uptime_hours", entry.get("online", "?")))) + "h"
        table.add_row(medal, username, score, earnings, online)

    console.print(table)

def cmd_ticket(args):
    """提交工单"""
    config = _require_auth()
    subject = args.subject
    content = " ".join(args.content)
    console.print(f"[bold]📝 正在提交工单...[/]")
    data = _api_post(config, "/api/tickets", {"subject": subject, "content": content, "type": "general"})
    if data.get("id") or data.get("success") or data.get("code") == 0:
        console.print(f"[bold green]✅ 工单已提交！管理员将尽快处理[/]")
    else:
        console.print(f"[red]❌ 提交失败: {data.get('message', data.get('detail', '未知错误'))}[/]")

def cmd_tickets(args):
    """查看工单列表"""
    config = _require_auth()
    data = _api_get(config, "/api/tickets")
    tickets = data if isinstance(data, list) else data.get("tickets", data.get("data", []))
    if not tickets:
        console.print("[yellow]📭 暂无工单[/]")
        return
    table = Table(title="📋 我的工单", box=box.ROUNDED, header_style="bold cyan")
    table.add_column("ID", style="dim", width=6)
    table.add_column("主题", min_width=20)
    table.add_column("状态", width=8)
    table.add_column("时间", width=16)
    for t in tickets:
        table.add_row(str(t.get("id","?")), (t.get("subject","") or "")[:30],
                      t.get("status","?"), (t.get("created_at","") or "")[:16])
    console.print(table)
