        icl	"src/ai.i"

;************************************************
;* resetAi
;*
;* Input : mission or active army has changed
;* Output: next computer unit can act without a leftover delay
;* Trash: a,flags; x/y preserved
;************************************************

resetAi

        lda	#0
        sta	ai.delay
        rts

;************************************************
;* aiTick
;*
;* Input : game/battle/help state; ai.delay and computer units
;* Output: one ready unit acts, delay advances, or turn finishes
;* Trash: a,x,y,flags; AI/game and renderer scratch
;************************************************

aiTick

        lda	app.screen
        beq	?aiInGame

        rts

?aiInGame
        lda	help.active
        beq	?aiNotInHelp

        rts

?aiNotInHelp
        lda	battle.active
        beq	?aiNotInBattle

        rts

?aiNotInBattle
        jsr	isComputerTurn

        bne	?aiCheckWinner

        rts

?aiCheckWinner
        lda	game.winner
        beq	?aiCheckDelay

        rts

?aiCheckDelay
        lda	ai.delay
        beq	?aiFindUnit

        dec	ai.delay
        rts

?aiFindUnit
        jsr	aiBuy

        ldx	#0

?aiUnitLoop
        lda	units.hp,x
        beq	?aiUnitNext

        lda	units.team,x
        cmp	game.team
        bne	?aiUnitNext

        lda	units.acted,x
        beq	?aiTakeUnit

?aiUnitNext
        inx
        cpx	app.unitCount
        bne	?aiUnitLoop

        jmp	nextTurn

?aiTakeUnit
        stx	ai.unit
        stx	game.selected
        lda	#0
        sta	game.mode
        sta	game.menuOpen
        sta	game.message
        lda	#AI_DELAY
        sta	ai.delay
        jsr	aiCapture

        lda	game.selected
        cmp	#NONE
        beq	?aiDone

        ldx	ai.unit
        jsr	airNeedsFuel

        bcs	?aiPlanUnit

        jsr	aiAttack

        lda	game.selected
        cmp	#NONE
        beq	?aiDone

?aiPlanUnit
        jsr	aiBuildDistances

        ldx	ai.unit
        lda	units.y,x
        asl
        asl
        asl
        asl
        clc
        adc	units.x,x
        sta	ai.origin
        tay
        lda	ai.distance,y
        cmp	#NONE
        bne	?aiPlanMove

        ; An isolated HQ must not prevent infantry from defending itself.
        jsr	aiClearDistances
        jsr	aiSeedAttackPositions
        jsr	aiFlood

?aiPlanMove
        jsr	buildMovement
        jsr	aiChooseDestination

        lda	ai.bestCell
        cmp	ai.origin
        beq	?aiAfterMove

        jsr	aiSetCursor
        jsr	action

?aiAfterMove
        jsr	aiCapture

        lda	game.selected
        cmp	#NONE
        beq	?aiDone

        jsr	getAiDifficulty

        cmp	#ai_level.EASY
        beq	?aiFinishUnit

        jsr	aiAttack

        lda	game.selected
        cmp	#NONE
        beq	?aiDone

?aiFinishUnit
        jmp	finishAction

?aiDone
        rts

;************************************************
;* aiCapture
;*
;* Input : ai.unit = selected computer unit
;* Output: captures a neutral/enemy property under ready infantry
;* Trash: a,x,y,flags; game and renderer scratch on capture
;************************************************

aiCapture

        ldx	ai.unit
        jsr	canCapture

        bcc	?aiCaptureDone

        jmp	captureBase

?aiCaptureDone
        rts

;************************************************
;* aiAttack
;*
;* Input : ai.unit; living enemy units
;* Output: cursor targets the weakest legal in-range enemy, then attacks
;* Trash: a,x,y,flags,scratch; AI/game and renderer scratch
;************************************************

aiAttack

        lda	#0
        sta	ai.attackScore
        lda	#NONE
        sta	ai.attackTarget
        sta	ai.attackHP
        lda	#0
        sta	ai.enemy

?aiAttackLoop
        ldy	ai.enemy
        ldx	ai.unit
        jsr	canAttack

        bcc	?aiAttackNext

        jsr	getAiDifficulty

        cmp	#ai_level.HARD
        beq	?aiHardTarget

        ldy	ai.enemy
        lda	units.hp,y
        cmp	ai.attackHP
        bcs	?aiAttackNext

        sta	ai.attackHP
        sty	ai.attackTarget
        jmp	?aiAttackNext

?aiHardTarget
        jsr	aiScoreTarget

        lda	ai.score
        cmp	ai.attackScore
        bcc	?aiAttackNext

        beq	?aiAttackNext

        sta	ai.attackScore
        ldy	ai.enemy
        sty	ai.attackTarget

?aiAttackNext
        inc	ai.enemy
        lda	ai.enemy
        cmp	app.unitCount
        bne	?aiAttackLoop

        ldy	ai.attackTarget
        cpy	#NONE
        beq	?aiAttackDone

        lda	units.x,y
        sta	game.cursorX
        lda	units.y,y
        sta	game.cursorY
        jmp	action

?aiAttackDone
        rts

;************************************************
;* aiBuildDistances
;*
;* Input : ai.unit, terrain and living enemy positions
;* Output: strategic BFS distances to HQ or enemy attack positions
;* Trash: a,x,y,flags; AI scratch and distance/queue arrays
;*
;* Actual movement still uses buildMovement for occupancy and MP.
;************************************************

aiBuildDistances

        jsr	aiClearDistances
        jsr	airPlanRefuel

        bcc	?aiOrdinaryGoal

        jmp	aiFlood

?aiOrdinaryGoal
        jsr	getAiDifficulty

        cmp	#ai_level.EASY
        beq	?aiGoalEnemies

        ldx	ai.unit
        lda	units.kind,x
        bne	?aiGoalEnemies

        lda	game.team
        eor	#1
        clc
        adc	#7
        sta	ai.enemyHQ
        ldy	#MAP_CELLS-1

?aiFindHQ
        lda	terrain,y
        cmp	ai.enemyHQ
        beq	?aiGoalHQ

        dey
        cpy	#NONE
        bne	?aiFindHQ

?aiGoalEnemies
        jsr	aiSeedAttackPositions

        jmp	aiFlood

?aiGoalHQ
        tya
        jsr	aiVisitCell

        jmp	aiFlood

;************************************************
;* getAiDifficulty
;*
;* Input : current army
;* Output: A = EASY/NORMAL/HARD; x preserved
;* Trash: a,y,flags
;************************************************

getAiDifficulty

        ldy	game.team
        lda	playerDifficulty,y
        rts

;************************************************
;* aiBuy
;*
;* Input : current computer army's budget, quota and free HQ
;* Output: at most one purchase using exactly the human rules
;* Trash: a,x,y,flags; economy scratch and roster on success
;************************************************

aiBuy

        jsr	airPurchase

        bcs	?aiBuyChoice

        jsr	getAiDifficulty

        tax
        lda	economy.cash,y
        cpx	#ai_level.EASY
        beq	?aiBuyInfantry

        cpx	#ai_level.HARD
        bne	?aiBuyRecon

        cmp	#7
        bcs	?aiBuyTank

        cmp	#6
        bcs	?aiBuyHowitzer

?aiBuyRecon
        cmp	#4
        bcc	?aiBuyInfantry

        lda	#2
        bne	?aiBuyChoice

?aiBuyTank
        lda	#1
        bne	?aiBuyChoice

?aiBuyHowitzer
        lda	#unit_kind.HOWITZER
        bne	?aiBuyChoice

?aiBuyInfantry
        lda	#0

?aiBuyChoice
        sta	economy.choice
        jmp	tryPurchase

;************************************************
;* aiScoreTarget
;*
;* Input : ai.enemy and ai.unit = legal firing pair
;* Output: ai.score favors guaranteed kills, then threat and wounds
;* Trash: a,x,y,flags,scratch; attack/AI scratch
;************************************************

aiScoreTarget

        ldy	ai.enemy
        lda	units.kind,y
        tay
        lda	unitValue,y
        asl
        asl
        asl
        sta	ai.score
        ldy	ai.enemy
        lda	#10
        sec
        sbc	units.hp,y
        clc
        adc	ai.score
        sta	ai.score
        ldx	ai.unit
        jsr	attackDamage

        cmp	units.hp,y
        bcc	?aiScoreDone

        lda	ai.score
        ora	#$80
        sta	ai.score

?aiScoreDone
        rts

;************************************************
;* aiClearDistances
;*
;* Input : ai.distance/queue state from the previous search
;* Output: empty queue and all strategic distances set to NONE
;* Trash: a,x,flags; AI search counters
;************************************************

aiClearDistances

        lda	#0
        sta	ai.head
        sta	ai.tail
        sta	ai.level
        lda	#NONE
        ldx	#MAP_CELLS-1

?aiClearLoop
        sta	ai.distance,x
        dex
        cpx	#NONE
        bne	?aiClearLoop

        rts

;************************************************
;* aiSeedAttackPositions
;*
;* Input : cleared BFS, ai.unit and living enemies
;* Output: seeds melee neighbors or howitzer firing-distance cells
;* Trash: a,x,y,flags; AI/attack scratch
;************************************************

aiSeedAttackPositions

        ldx	ai.unit
        lda	units.kind,x
        cmp	#unit_kind.HOWITZER
        beq	aiSeedFiringPositions

        jmp	aiSeedEnemies

;************************************************
;* aiSeedFiringPositions
;*
;* Input : cleared BFS and ai.unit = howitzer
;* Output: walkable cells at legal firing distance seeded at zero
;* Trash: a,x,y,flags,scratch; AI/attack scratch and BFS arrays
;*
;* Occupancy and weighted MP are checked by buildMovement later.
;************************************************

aiSeedFiringPositions

        lda	#0
        sta	ai.cell
        sta	ai.level

?aiFiringCell
        ldy	ai.cell
        jsr	movementCost

        cmp	#NONE
        beq	?aiFiringNextCell

        lda	#0
        sta	ai.enemy

?aiFiringEnemy
        ldx	ai.enemy
        lda	units.hp,x
        beq	?aiFiringNextEnemy

        lda	units.team,x
        cmp	game.team
        beq	?aiFiringNextEnemy

        txa
        tay
        ldx	ai.unit
        jsr	canHitClass

        bcc	?aiFiringNextEnemy

        ldx	ai.enemy
        lda	ai.cell
        and	#15
        sta	attack.x
        lda	ai.cell
        lsr
        lsr
        lsr
        lsr
        sta	attack.y
        jsr	distanceToPosition

        ldx	ai.unit
        jsr	distanceInRange

        bcc	?aiFiringNextEnemy

        lda	ai.cell
        jsr	aiVisitCell

        jmp	?aiFiringNextCell

?aiFiringNextEnemy
        inc	ai.enemy
        lda	ai.enemy
        cmp	app.unitCount
        bne	?aiFiringEnemy

?aiFiringNextCell
        inc	ai.cell
        lda	ai.cell
        cmp	#MAP_CELLS
        bne	?aiFiringCell

        rts

;************************************************
;* aiSeedEnemies
;*
;* Input : cleared BFS state and living enemy units
;* Output: walkable enemy-adjacent cells seeded at distance zero
;* Trash: a,x,y,flags; AI search scratch
;************************************************

aiSeedEnemies

        lda	#0
        sta	ai.enemy
        sta	ai.level

?aiSeedLoop
        ldx	ai.enemy
        lda	units.hp,x
        beq	?aiSeedNext

        lda	units.team,x
        cmp	game.team
        beq	?aiSeedNext

        txa
        tay
        ldx	ai.unit
        jsr	canHitClass

        bcc	?aiSeedNext

        ldx	ai.enemy
        lda	units.y,x
        asl
        asl
        asl
        asl
        clc
        adc	units.x,x
        sta	ai.cell
        jsr	aiNeighbors

?aiSeedNext
        inc	ai.enemy
        lda	ai.enemy
        cmp	app.unitCount
        bne	?aiSeedLoop

        rts

;************************************************
;* aiFlood
;*
;* Input : seeded ai.queue/distance and terrain costs
;* Output: distances propagated through every reachable walkable cell
;* Trash: a,x,y,flags; AI search scratch and arrays
;************************************************

aiFlood

        ldx	ai.head
        cpx	ai.tail
        beq	?aiFloodDone

        lda	ai.queue,x
        sta	ai.cell
        tay
        lda	ai.distance,y
        clc
        adc	#1
        sta	ai.level
        inc	ai.head
        jsr	aiNeighbors

        jmp	aiFlood

?aiFloodDone
        rts

;************************************************
;* aiNeighbors
;*
;* Input : ai.cell and ai.level
;* Output: visits orthogonal in-bounds neighbors without row wrapping
;* Trash: a,x,y,flags; AI search scratch
;************************************************

aiNeighbors

        lda	ai.cell
        cmp	#MAP_WIDTH
        bcc	?aiNeighborEast

        sec
        sbc	#MAP_WIDTH
        jsr	aiVisitCell

?aiNeighborEast
        lda	ai.cell
        and	#15
        cmp	#15
        beq	?aiNeighborSouth

        lda	ai.cell
        clc
        adc	#1
        jsr	aiVisitCell

?aiNeighborSouth
        lda	ai.cell
        cmp	#MAP_CELLS-MAP_WIDTH
        bcs	?aiNeighborWest

        clc
        adc	#MAP_WIDTH
        jsr	aiVisitCell

?aiNeighborWest
        lda	ai.cell
        and	#15
        beq	?aiNeighborsDone

        lda	ai.cell
        sec
        sbc	#1
        jsr	aiVisitCell

?aiNeighborsDone
        rts

;************************************************
;* aiVisitCell
;*
;* Input : A = map index, ai.level = proposed distance
;* Output: unvisited walkable cell added once to the BFS queue
;* Trash: a,x,y,flags; ai.distance/queue/tail
;************************************************

aiVisitCell

        tay
        lda	ai.distance,y
        cmp	#NONE
        bne	?aiVisitDone

        jsr	movementCost

        cmp	#NONE
        beq	?aiVisitDone

        lda	ai.level
        sta	ai.distance,y
        tya
        ldx	ai.tail
        sta	ai.queue,x
        inc	ai.tail

?aiVisitDone
        rts

;************************************************
;* aiChooseDestination
;*
;* Input : legal movement map, strategic distances, ai.unit/origin
;* Output: bestCell/distance/MP, preferring progress then remaining MP
;* Trash: a,x,y,flags; AI destination scratch
;************************************************

aiChooseDestination

        ldy	ai.origin
        sty	ai.bestCell
        lda	ai.distance,y
        sta	ai.bestDistance
        ldx	ai.unit
        lda	units.mp,x
        sta	ai.bestMP
        lda	#0
        sta	ai.cell

?aiDestinationLoop
        ldy	ai.cell
        lda	movement.reachable,y
        cmp	#NONE
        beq	?aiDestinationNext

        lda	movement.occupied,y
        cmp	#NONE
        bne	?aiDestinationNext

        lda	ai.distance,y
        cmp	#NONE
        beq	?aiDestinationNext

        cmp	ai.bestDistance
        bcc	?aiDestinationBetter

        bne	?aiDestinationNext

        lda	movement.reachable,y
        cmp	ai.bestMP
        bcc	?aiDestinationNext

        beq	?aiDestinationNext

?aiDestinationBetter
        lda	ai.distance,y
        sta	ai.bestDistance
        lda	movement.reachable,y
        sta	ai.bestMP
        sty	ai.bestCell

?aiDestinationNext
        inc	ai.cell
        lda	ai.cell
        cmp	#MAP_CELLS
        bne	?aiDestinationLoop

        rts

;************************************************
;* aiSetCursor
;*
;* Input : A = ai.bestCell
;* Output: game.cursorX/Y set to that map cell
;* Trash: a,flags; x/y preserved
;************************************************

aiSetCursor

        and	#15
        sta	game.cursorX
        lda	ai.bestCell
        lsr
        lsr
        lsr
        lsr
        sta	game.cursorY
        rts
