import { isAbsolute, posix } from 'node:path'
import { matchesAnyGlob } from '../check/glob'
import { isInSettledSection } from './board-row'
import { ALLOWED_TOPICS, isForbiddenTopic, isSettledTopic, type SettledTopic } from './topics'

/** A lane question the coordinator answers itself, as `jh settled` received it; evidence and topic may be absent. */
export type SettledRequest = {
  lane: string
  question: string
  answer: string
  /** `file:line`, relative to the checkout the command runs in. */
  evidence: string | null
  topic: string | null
  wayBack: string | null
}

export type Evidence = { path: string; line: number }

/** A request that passed every check: the topic is an allowed one, the evidence a line inside the checkout. */
export type CheckedRequest = Omit<SettledRequest, 'evidence' | 'topic'> & { evidence: Evidence; topic: SettledTopic }

export const REFUSAL = {
  topicMissing: 'topicMissing',
  topicUnknown: 'topicUnknown',
  topicForbidden: 'topicForbidden',
  evidenceMissing: 'evidenceMissing',
  evidenceFormat: 'evidenceFormat',
  evidenceOutside: 'evidenceOutside',
  fileMissing: 'fileMissing',
  lineMissing: 'lineMissing',
  lineWithoutDecision: 'lineWithoutDecision',
  evidenceSelfReference: 'evidenceSelfReference',
} as const

export type RefusalReason = (typeof REFUSAL)[keyof typeof REFUSAL]

export type Refusal = { reason: RefusalReason; detail: string }

export type CheckResult = { refusal: Refusal } | { checked: CheckedRequest }

/** Reads a file by its path relative to the checkout; null when there is none. */
export type EvidenceReader = (path: string) => string | null

/**
 * Files whose every line is evidence: they are rules an agent follows, written for that purpose. Fixed in the
 * package, not a config key: a project that could widen this list could turn any file into evidence.
 */
const RULE_AND_SKILL_FILES: readonly string[] = [
  '.claude/rules/**/*.md',
  '.claude/skills/*/SKILL.md',
  '.claude/project/*.md',
  'CLAUDE.md',
]

const EVIDENCE = /^(.+):([1-9]\d*)$/
const DATE = /\b\d{4}-\d{2}-\d{2}\b|\b\d{1,2}\.\d{1,2}\./
const USER = /\bUser\b/

/** `file:line` split at the last colon; null when the line is not a positive whole number. */
export const parseEvidence = (text: string): Evidence | null => {
  const match = EVIDENCE.exec(text.trim())
  return match ? { path: match[1], line: Number(match[2]) } : null
}

export const isRuleOrSkillFile = (path: string): boolean => matchesAnyGlob(path, RULE_AND_SKILL_FILES)

/** A line that records a decision of the user: a date and the word `User`, as plans and boards write it. */
export const carriesUserDecision = (line: string): boolean => DATE.test(line) && USER.test(line)

/** The path normalised inside the checkout; null when it is absolute or leaves the checkout. */
const insideCheckout = (path: string): string | null => {
  if (isAbsolute(path)) return null
  const normalised = posix.normalize(path)
  return normalised === '..' || normalised.startsWith('../') ? null : normalised
}

const topicCheck = (topic: string | null): Refusal | SettledTopic => {
  if (topic === null)
    return { reason: REFUSAL.topicMissing, detail: `--topic is required: ${ALLOWED_TOPICS.join(', ')}` }
  if (!isSettledTopic(topic))
    return { reason: REFUSAL.topicUnknown, detail: `unknown topic ${topic}; one of ${ALLOWED_TOPICS.join(', ')}` }
  return isForbiddenTopic(topic)
    ? { reason: REFUSAL.topicForbidden, detail: `${topic} is the user's decision, never settled in a lane's place` }
    : topic
}

const lineRefusal = (evidence: Evidence, text: string): Refusal | null => {
  const lines = text.split('\n')
  if (evidence.line > lines.length)
    return { reason: REFUSAL.lineMissing, detail: `${evidence.path} has ${lines.length} lines, not ${evidence.line}` }
  if (isInSettledSection(lines, evidence.line - 1))
    return {
      reason: REFUSAL.evidenceSelfReference,
      detail: `${evidence.path}:${evidence.line} is a settled answer itself, not the decision it rests on`,
    }
  if (isRuleOrSkillFile(evidence.path) || carriesUserDecision(lines[evidence.line - 1])) return null
  return {
    reason: REFUSAL.lineWithoutDecision,
    detail: `${evidence.path}:${evidence.line} carries no date with "User" and is no rule or skill file`,
  }
}

const evidenceCheck = (text: string | null, read: EvidenceReader): Refusal | Evidence => {
  if (text === null) return { reason: REFUSAL.evidenceMissing, detail: '--evidence <file:line> is required' }
  const parsed = parseEvidence(text)
  if (!parsed) return { reason: REFUSAL.evidenceFormat, detail: `${text} is not <file>:<line>` }
  const path = insideCheckout(parsed.path)
  if (path === null) return { reason: REFUSAL.evidenceOutside, detail: `${parsed.path} lies outside the checkout` }
  const content = read(path)
  if (content === null) return { reason: REFUSAL.fileMissing, detail: `${path} does not exist` }
  const evidence = { path, line: parsed.line }
  return lineRefusal(evidence, content) ?? evidence
}

const isRefusal = (value: Refusal | Evidence | SettledTopic): value is Refusal =>
  typeof value === 'object' && 'reason' in value

/**
 * The request ready to settle, or why the coordinator may not settle it itself. The topic is checked first, so a
 * forbidden topic is refused before any file is read; then the evidence: the file exists in the checkout, the line
 * exists, and it records a dated decision of the user unless the file is a rule or skill file.
 */
export const checkSettled = (request: SettledRequest, read: EvidenceReader): CheckResult => {
  const topic = topicCheck(request.topic)
  if (isRefusal(topic)) return { refusal: topic }
  const evidence = evidenceCheck(request.evidence, read)
  if (isRefusal(evidence)) return { refusal: evidence }
  return { checked: { ...request, topic, evidence } }
}
