#!/usr/bin/env node
import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import process from 'node:process';

const baseUrl = (process.env.ITDOG_API_BASE || 'https://itdog.org').replace(/\/$/, '');
const configDir = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'itdog');
const configPath = path.join(configDir, 'cli-token');

function usage() {
  process.stdout.write('ITDOG CLI\n\n  itdog-cli auth login|status|logout\n  itdog-cli api GET /api/me\n  itdog-cli api POST /api/posts \'{"title":"..."}\'\n\n普通账号 CLI 发帖限制：每天最多发布 10 篇；每张图片不超过 200 KB；视频不超过 20 MB，且需先上传到 ITDOG。\n');
}

async function readToken() {
  try { return (await readFile(configPath, 'utf8')).trim(); }
  catch { return ''; }
}

function promptSecret(label) {
  return new Promise((resolve, reject) => {
    if (!process.stdin.isTTY) {
      reject(new Error('请在交互式终端中运行登录命令。'));
      return;
    }
    process.stdout.write(label);
    const input = process.stdin;
    const wasRaw = input.isRaw;
    input.setRawMode(true);
    input.resume();
    let value = '';
    const cleanup = () => {
      input.removeListener('data', onData);
      input.setRawMode(Boolean(wasRaw));
      input.pause();
      process.stdout.write('\n');
    };
    const onData = (chunk) => {
      for (const char of chunk.toString('utf8')) {
        if (char === '\u0003') { cleanup(); reject(new Error('已取消。')); return; }
        if (char === '\r' || char === '\n') { cleanup(); resolve(value.trim()); return; }
        if (char === '\u007f' || char === '\b') value = value.slice(0, -1);
        else if (char >= ' ') value += char;
      }
    };
    input.on('data', onData);
  });
}

async function apiRequest(token, method, apiPath, body) {
  if (!apiPath.startsWith('/api/') || apiPath.startsWith('//')) throw new Error('路径必须是站内 /api/ 接口。');
  const url = new URL(apiPath, baseUrl);
  if (url.origin !== baseUrl) throw new Error('只允许请求 ITDOG API。');
  const response = await fetch(url, {
    method,
    headers: {
      authorization: `Bearer ${token}`,
      accept: 'application/json',
      ...(body === undefined ? {} : { 'content-type':'application/json' })
    },
    body: body === undefined ? undefined : JSON.stringify(body)
  });
  const text = await response.text();
  let payload;
  try { payload = JSON.parse(text); } catch { payload = text; }
  if (!response.ok) throw new Error(payload?.error || `API 请求失败（${response.status}）`);
  return payload;
}

async function main() {
  const [command, subcommand, ...args] = process.argv.slice(2);
  if (command === 'help' || command === '--help' || !command) { usage(); return; }
  if (command === 'auth' && subcommand === 'login') {
    const token = await promptSecret('粘贴个人设置中生成的 ITDOG CLI 密钥（输入不显示）：');
    if (!/^sk-itdog_[a-f0-9]{64}$/.test(token)) throw new Error('密钥格式无效。');
    const identity = await apiRequest(token, 'GET', '/api/me');
    if (identity.user?.role !== 'user') throw new Error('仅普通权限账号可以使用 CLI。');
    await mkdir(configDir, { recursive:true, mode:0o700 });
    await writeFile(configPath, token + '\n', { mode:0o600 });
    await chmod(configDir, 0o700);
    await chmod(configPath, 0o600);
    process.stdout.write(`已登录：${identity.user.profile?.name || 'ITDOG 用户'}\n`);
    return;
  }
  if (command === 'auth' && subcommand === 'logout') {
    await rm(configPath, { force:true });
    process.stdout.write('本机 CLI 密钥已清除。\n');
    return;
  }
  const token = await readToken();
  if (!token) throw new Error('尚未登录。先运行 itdog-cli auth login。');
  if (command === 'auth' && subcommand === 'status') {
    const identity = await apiRequest(token, 'GET', '/api/me');
    process.stdout.write(`已登录：${identity.user.profile?.name || 'ITDOG 用户'}（普通权限）\n`);
    return;
  }
  if (command === 'api') {
    const method = String(subcommand || 'GET').toUpperCase();
    const apiPath = args[0] || '';
    const body = args[1] ? JSON.parse(args[1]) : undefined;
    const result = await apiRequest(token, method, apiPath, body);
    process.stdout.write(JSON.stringify(result, null, 2) + '\n');
    return;
  }
  usage();
}

main().catch((error) => {
  process.stderr.write((error.message || '命令执行失败。') + '\n');
  process.exitCode = 1;
});
