import { promises as fs } from 'fs';
import path from 'path';
import os from 'os';

const CREDENTIALS_DIR = path.join(os.homedir(), '.textnow');
const CREDENTIALS_FILE = path.join(CREDENTIALS_DIR, 'credentials.json');

/**
 * Parse a cookie string into an object
 */
export function parseCookies(cookieString) {
  const cookies = {};
  if (!cookieString) return cookies;
  
  cookieString.split(';').forEach(cookie => {
    const [name, ...valueParts] = cookie.trim().split('=');
    if (name) {
      cookies[name.trim()] = valueParts.join('=').trim();
    }
  });
  
  return cookies;
}

/**
 * Extract important cookies for API calls
 */
export function extractAuthCookies(cookieString) {
  const parsed = parseCookies(cookieString);
  return {
    connectSid: parsed['connect.sid'] || null,
    csrf: parsed['_csrf'] || null,
    xsrfToken: parsed['XSRF-TOKEN'] || null,
    tnSessionId: parsed['tn_session_id'] || null,
  };
}

/**
 * Try to extract username from cookies or profile data
 */
export function extractUsername(cookieString) {
  const parsed = parseCookies(cookieString);
  // TextNow sometimes stores username in cookies
  if (parsed['tn_username']) return parsed['tn_username'];
  if (parsed['username']) return parsed['username'];
  return null;
}

/**
 * Save credentials to file
 */
export async function saveCredentials(data) {
  await fs.mkdir(CREDENTIALS_DIR, { recursive: true });
  
  const credentials = {
    username: data.username || null,
    cookies: data.cookies,
    authCookies: extractAuthCookies(data.cookies),
    savedAt: new Date().toISOString(),
  };
  
  await fs.writeFile(CREDENTIALS_FILE, JSON.stringify(credentials, null, 2));
  return credentials;
}

/**
 * Load credentials from file
 */
export async function loadCredentials() {
  try {
    const content = await fs.readFile(CREDENTIALS_FILE, 'utf-8');
    return JSON.parse(content);
  } catch (err) {
    if (err.code === 'ENOENT') {
      return null;
    }
    throw err;
  }
}

/**
 * Update credentials (e.g., to add username after fetching profile)
 */
export async function updateCredentials(updates) {
  const current = await loadCredentials();
  if (!current) throw new Error('No credentials found');
  
  const updated = { ...current, ...updates, updatedAt: new Date().toISOString() };
  await fs.writeFile(CREDENTIALS_FILE, JSON.stringify(updated, null, 2));
  return updated;
}

/**
 * Check if credentials exist
 */
export async function hasCredentials() {
  try {
    await fs.access(CREDENTIALS_FILE);
    return true;
  } catch {
    return false;
  }
}
