/**
 * Trust Command - Manage trust scores and endorsements
 */

import { Command } from 'commander';
import { getConfig, getIdentity } from '../config.js';
import { createLogger, createTrustSystem } from '@highway1/core';
import { homedir } from 'os';
import { join } from 'path';

const logger = createLogger('cli:trust');

export function createTrustCommand(): Command {
  const trust = new Command('trust')
    .description('Manage trust scores and endorsements');

  // Show trust score
  trust
    .command('show')
    .description('Show trust score for an agent')
    .argument('<did>', 'Agent DID')
    .action(async (did: string) => {
      try {
        const dataDir = join(homedir(), '.clawiverse');
        const trustSystem = createTrustSystem({
          dbPath: `${dataDir}/trust`,
          getPublicKey: async () => new Uint8Array(), // Placeholder
        });

        await trustSystem.start();

        const score = await trustSystem.getTrustScore(did);
        const endorsements = await trustSystem.getEndorsements(did);

        console.log('\n📊 Trust Score for', did);
        console.log('─'.repeat(60));
        console.log(`Interaction Score:  ${(score.interactionScore * 100).toFixed(1)}%`);
        console.log(`Endorsements:       ${score.endorsements}`);
        console.log(`Completion Rate:    ${(score.completionRate * 100).toFixed(1)}%`);
        console.log(`Response Time:      ${score.responseTime.toFixed(0)}ms`);
        console.log(`Uptime:            ${(score.uptime * 100).toFixed(1)}%`);
        console.log(`Last Updated:       ${new Date(score.lastUpdated).toLocaleString()}`);

        if (endorsements.length > 0) {
          console.log('\n✨ Endorsements:');
          for (const e of endorsements) {
            console.log(`  • From: ${e.from}`);
            console.log(`    Score: ${(e.score * 100).toFixed(0)}%`);
            console.log(`    Reason: ${e.reason}`);
            console.log(`    Date: ${new Date(e.timestamp).toLocaleDateString()}`);
          }
        }

        await trustSystem.stop();
      } catch (error) {
        logger.error('Failed to show trust score', error);
        console.error('Error:', error instanceof Error ? error.message : error);
        process.exit(1);
      }
    });

  // Endorse an agent
  trust
    .command('endorse')
    .description('Endorse an agent')
    .argument('<did>', 'Agent DID to endorse')
    .option('-s, --score <score>', 'Endorsement score (0-1)', '0.8')
    .option('-r, --reason <reason>', 'Reason for endorsement', 'Good collaboration')
    .action(async (did: string, options: { score: string; reason: string }) => {
      try {
        const dataDir = join(homedir(), '.clawiverse');
        const trustSystem = createTrustSystem({
          dbPath: `${dataDir}/trust`,
          getPublicKey: async () => new Uint8Array(), // Placeholder
        });

        await trustSystem.start();

        const score = parseFloat(options.score);
        if (isNaN(score) || score < 0 || score > 1) {
          throw new Error('Score must be between 0 and 1');
        }

        // Load identity for signing
        const identity = getIdentity();
        if (!identity) {
          throw new Error('No identity found. Run "hw1 init" first.');
        }

        const { importKeyPair } = await import('@highway1/core');
        const keyPair = importKeyPair({
          publicKey: identity.publicKey,
          privateKey: identity.privateKey,
        });

        const endorsement = await trustSystem.endorse(
          identity.did,
          did,
          score,
          options.reason,
          keyPair.sign
        );

        console.log('\n✅ Endorsement created');
        console.log(`From: ${endorsement.from}`);
        console.log(`To: ${endorsement.to}`);
        console.log(`Score: ${(endorsement.score * 100).toFixed(0)}%`);
        console.log(`Reason: ${endorsement.reason}`);

        await trustSystem.stop();
      } catch (error) {
        logger.error('Failed to endorse agent', error);
        console.error('Error:', error instanceof Error ? error.message : error);
        process.exit(1);
      }
    });

  // Show interaction history
  trust
    .command('history')
    .description('Show interaction history with an agent')
    .argument('<did>', 'Agent DID')
    .option('-l, --limit <limit>', 'Number of interactions to show', '10')
    .action(async (did: string, options: { limit: string }) => {
      try {
        const dataDir = join(homedir(), '.clawiverse');
        const trustSystem = createTrustSystem({
          dbPath: `${dataDir}/trust`,
          getPublicKey: async () => new Uint8Array(), // Placeholder
        });

        await trustSystem.start();

        const limit = parseInt(options.limit, 10);
        const history = await trustSystem.getHistory(did, limit);

        console.log(`\n📜 Interaction History with ${did}`);
        console.log('─'.repeat(60));

        if (history.length === 0) {
          console.log('No interactions recorded');
        } else {
          for (const interaction of history) {
            const status = interaction.success ? '✅' : '❌';
            console.log(`${status} ${interaction.type} - ${new Date(interaction.timestamp).toLocaleString()}`);
            console.log(`   Response time: ${interaction.responseTime}ms`);
            if (interaction.rating) {
              console.log(`   Rating: ${'⭐'.repeat(interaction.rating)}`);
            }
            if (interaction.feedback) {
              console.log(`   Feedback: ${interaction.feedback}`);
            }
          }
        }

        await trustSystem.stop();
      } catch (error) {
        logger.error('Failed to show history', error);
        console.error('Error:', error instanceof Error ? error.message : error);
        process.exit(1);
      }
    });

  // Show trust statistics
  trust
    .command('stats')
    .description('Show local trust statistics')
    .action(async () => {
      try {
        const dataDir = join(homedir(), '.clawiverse');
        const trustSystem = createTrustSystem({
          dbPath: `${dataDir}/trust`,
          getPublicKey: async () => new Uint8Array(), // Placeholder
        });

        await trustSystem.start();

        // Get all agents from interaction history
        const { InteractionHistory } = await import('@highway1/core');
        const history = new InteractionHistory(`${dataDir}/trust/interactions`);
        await history.open();

        const agents = await history.getAllAgents();

        console.log('\n📊 Trust Statistics');
        console.log('─'.repeat(60));
        console.log(`Total agents tracked: ${agents.length}`);

        if (agents.length > 0) {
          console.log('\nTop agents by trust score:');
          const scores = await Promise.all(
            agents.map(async (did) => ({
              did,
              score: await trustSystem.getTrustScore(did),
            }))
          );

          scores.sort((a, b) => b.score.interactionScore - a.score.interactionScore);

          for (const { did, score } of scores.slice(0, 5)) {
            console.log(`  ${(score.interactionScore * 100).toFixed(0)}% - ${did}`);
          }
        }

        await history.close();
        await trustSystem.stop();
      } catch (error) {
        logger.error('Failed to show stats', error);
        console.error('Error:', error instanceof Error ? error.message : error);
        process.exit(1);
      }
    });

  return trust;
}
