import { Card, CardContent } from "@/components/ui/card";

async function getMarkets() {
  const DB = "/home/fzq1228/polyscout/data/polyscout.db";
  const { execSync } = await import("child_process");
  const py = `import sqlite3,json; conn=sqlite3.connect('${DB}'); c=conn.cursor(); c.execute("""SELECT market_id, question, round(liquidity,2), round(volume,2), end_date FROM markets ORDER BY liquidity DESC LIMIT 50"""); print(json.dumps(c.fetchall(), ensure_ascii=False, default=str)); conn.close()`;
  try { return JSON.parse(execSync(`python3 -c ${JSON.stringify(py)}`, { encoding: "utf8" })); }
  catch { return []; }
}

export default async function MarketsPage() {
  const rows = await getMarkets();
  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">市场列表</h1>
        <p className="text-muted-foreground text-sm mt-1">按流动性排序，Top 50</p>
      </div>
      <Card>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border">
                  <th className="text-left px-4 py-3 text-muted-foreground font-medium text-xs uppercase tracking-wider">市场ID</th>
                  <th className="text-left px-4 py-3 text-muted-foreground font-medium text-xs uppercase tracking-wider">问题</th>
                  <th className="text-left px-4 py-3 text-muted-foreground font-medium text-xs uppercase tracking-wider">流动性</th>
                  <th className="text-left px-4 py-3 text-muted-foreground font-medium text-xs uppercase tracking-wider hidden md:table-cell">成交量</th>
                  <th className="text-left px-4 py-3 text-muted-foreground font-medium text-xs uppercase tracking-wider hidden md:table-cell">截止日期</th>
                </tr>
              </thead>
              <tbody>
                {rows.length === 0 ? (
                  <tr><td colSpan={5} className="text-center py-8 text-muted-foreground">暂无数据</td></tr>
                ) : rows.map((r: any[], i: number) => (
                  <tr key={i} className="border-b border-border last:border-0 hover:bg-accent/50 transition-colors">
                    <td className="px-4 py-3 font-mono text-xs text-muted-foreground">{String(r[0]).slice(0, 10)}</td>
                    <td className="px-4 py-3 max-w-xs truncate">{r[1]}</td>
                    <td className="px-4 py-3">${Number(r[2]).toLocaleString()}</td>
                    <td className="px-4 py-3 hidden md:table-cell">${Number(r[3]).toLocaleString()}</td>
                    <td className="px-4 py-3 font-mono text-xs text-muted-foreground hidden md:table-cell">{String(r[4]).slice(0, 10)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
