# frozen_string_literal: true

module SaneMasterModules
  # Session lifecycle management - insights extraction at session end
  # Inspired by Auto-Claude's automated insight extraction pattern
  module Session
    INSIGHT_CATEGORIES = {
      bug_pattern: {
        prompt: 'Any bug patterns discovered this session?',
        prefix: 'BugPattern',
        example: 'e.g., "await scheduleSegment hangs in offline mode"'
      },
      concurrency_gotcha: {
        prompt: 'Any concurrency gotchas worth remembering?',
        prefix: 'ConcurrencyGotcha',
        example: 'e.g., "MainActor.assumeIsolated crashes in deinit"'
      },
      architecture_pattern: {
        prompt: 'Any architecture decisions or patterns?',
        prefix: 'ArchPattern',
        example: 'e.g., "Use type erasure for macOS 26+ APIs"'
      }
    }.freeze

    def session_end(args)
      puts '🔚 --- [ SESSION END REVIEW ] ---'
      puts ''
      puts 'Checking for memory-worthy insights from this session...'
      puts '(Inspired by Auto-Claude insight extraction pattern)'
      puts ''

      insights = []
      skip_prompts = args.include?('--skip-prompts')

      if skip_prompts
        puts '⏭️  Skipping interactive prompts (--skip-prompts)'
        show_session_summary
        return
      end

      INSIGHT_CATEGORIES.each do |category, config|
        insight = prompt_for_insight(category, config)
        insights << insight if insight
      end

      if insights.empty?
        puts ''
        puts '✅ No new insights to record. Session complete!'
        show_session_summary
        return
      end

      # Record insights to memory
      puts ''
      puts "📝 Recording #{insights.count} insight(s) to memory..."
      insights.each do |insight|
        auto_record(insight[:type].to_s, insight[:name], insight[:observations])
      end

      puts ''
      puts '✅ Session insights saved!'
      generate_handoff
      show_session_summary
    end

    def generate_handoff
      handoff_path = File.join(Dir.pwd, '.claude', 'SESSION_HANDOFF.md')
      FileUtils.mkdir_p(File.dirname(handoff_path))

      # Gather info
      recent_commits = `git log --oneline -10 --format='%h %s' 2>/dev/null`.strip.split("\n")
      git_status = `git status --short 2>/dev/null`.strip
      timestamp = Time.now.strftime('%Y-%m-%d %H:%M')

      content = <<~HANDOFF
        # Session Handoff - #{timestamp}

        ## Recent Commits
        #{recent_commits.map { |c| "- #{c}" }.join("\n")}

        ## Uncommitted Changes
        ```
        #{git_status.empty? ? '(none)' : git_status}
        ```

        ## In Progress
        <!-- Add notes about incomplete work -->

        ## Known Issues
        <!-- Add notes about bugs or problems -->

        ## Next Steps
        <!-- Add recommended next actions -->

        ---
        *Generated by `./scripts/SaneMaster.rb session_end`*
      HANDOFF

      File.write(handoff_path, content)
      puts '📋 Handoff file generated: .claude/SESSION_HANDOFF.md'
    end

    private

    def prompt_for_insight(category, config)
      puts(config[:prompt])
      puts "   #{config[:example]}"
      print '   (y/n): '

      response = $stdin.gets&.chomp&.downcase
      return nil unless response == 'y'

      puts ''
      print '   Name (short, snake_case): '
      name = $stdin.gets&.chomp
      return nil if name.nil? || name.empty?

      # Clean up the name
      name = name.downcase.gsub(/\s+/, '_').gsub(/[^a-z0-9_]/, '')
      full_name = "#{config[:prefix]}_#{Date.today.strftime('%Y%m%d')}_#{name}"

      puts '   Enter observations (one per line, empty line to finish):'
      observations = []
      loop do
        print '   > '
        line = $stdin.gets&.chomp
        break if line.nil? || line.empty?

        observations << line
      end

      return nil if observations.empty?

      puts "   ✓ Will record: #{full_name}"
      puts ''

      {
        type: category,
        name: full_name,
        observations: observations
      }
    end

    def show_session_summary
      puts ''
      puts '=' * 60
      puts '  SESSION SUMMARY TEMPLATE'
      puts '  (Rate RULE COMPLIANCE, not task completion)'
      puts '=' * 60
      puts ''
      puts '## Session Summary'
      puts ''
      puts '### What Was Done'

      # Show recent git commits as numbered list
      recent_commits = `git log --oneline -5 --format='%s' 2>/dev/null`.strip.split("\n")
      if recent_commits.any?
        recent_commits.each_with_index { |c, i| puts "#{i + 1}. #{c}" }
      else
        puts '1. [Describe what was done]'
      end

      puts ''
      puts '### SOP Compliance: X/10'
      puts ''
      puts '✅ **Followed:**'
      puts '- Rule #X: [What you did right]'
      puts '- Rule #X: [What you did right]'
      puts ''
      puts '❌ **Missed:**'
      puts '- Rule #X: [What you missed and why]'
      puts ''
      puts '**Next time:** [Specific improvement]'
      puts ''
      puts '### Followup'
      puts '- [Actionable item for future]'
      puts ''
      puts '=' * 60
      puts ''

      # Show memory stats
      memory = load_memory
      if memory && memory['entities']
        entities = memory['entities']
        entity_count = entities.count
        estimated_tokens = (memory.to_json.length / 4.0).round

        puts "📊 Memory: #{entity_count} entities (~#{estimated_tokens} tokens)"
        puts "   ⚠️  Entity count HIGH (#{entity_count}/60)" if entity_count > 60
        puts "   ⚠️  Token count HIGH (~#{estimated_tokens}/8000)" if estimated_tokens > 8000
      end

      # Show compliance report if audit log exists
      audit_log = File.join(Dir.pwd, '.claude', 'audit_log.jsonl')
      return unless File.exist?(audit_log) && File.size(audit_log).positive?

      require_relative 'compliance_report'
      SaneMasterModules::ComplianceReport.generate
    end
  end
end
