using System.Text.Json;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace JobTrackerApi.Controllers;

// Phase 5 — the AI Workspace for one job application. Every module runs through ISummarizerService and
// is stored as append-only history; nothing is applied automatically. docs/architecture/ai-career-assistant.md.
[ApiController]
[Route("api/jobapplications/{jobId:int}/ai")]
[Authorize(AuthenticationSchemes = "local")]
public sealed class AiWorkspaceController : ControllerBase
{
    private readonly UserManager<ApplicationUser> _users;
    private readonly IAiWorkspaceService _workspace;
    private readonly IConfiguration _config;
    private readonly JobTrackerApi.Data.JobTrackerContext? _db;

    public AiWorkspaceController(UserManager<ApplicationUser> users, IAiWorkspaceService workspace, IConfiguration config, JobTrackerApi.Data.JobTrackerContext? db = null)
    {
        _users = users;
        _workspace = workspace;
        _config = config;
        _db = db;
    }

    public sealed record GenerateRequest(string Module, string? Mode, string? ExtraContext);
    public sealed record InteractionDto(int Id, string Module, string? Mode, string Title, string Provider, JsonElement Result, int InputCharacterCount, int OutputCharacterCount, int EstimatedTokenCount, DateTimeOffset CreatedAtUtc);

    [HttpGet("modules")]
    public ActionResult<object> Modules() => Ok(new { modules = _workspace.Modules, provider = ResolveProvider() });

    [HttpPost("generate")]
    [Authorize(Policy = ProEntitlement.Policy)]
    public async Task<ActionResult<InteractionDto>> Generate(int jobId, [FromBody] GenerateRequest request, CancellationToken ct)
    {
        var user = await _users.GetUserAsync(User);
        if (user is null) return Unauthorized();
        if (string.IsNullOrWhiteSpace(request?.Module)) return BadRequest("Choose an AI module.");

        if (_db is not null)
        {
            var roles = await _users.GetRolesAsync(user);
            var entitlements = AccountPlans.ForRoles(roles);
            var monthStart = new DateTimeOffset(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1, 0, 0, 0, TimeSpan.Zero);
            var interactions = _db.AiInteractions.Where(x => x.OwnerUserId == user.Id);
            int usedCalls;
            long usedTokens;
            if (_db.Database.IsSqlite())
            {
                var used = (await interactions
                    .Select(x => new { x.CreatedAtUtc, x.EstimatedTokenCount })
                    .ToListAsync(ct))
                    .Where(x => x.CreatedAtUtc >= monthStart)
                    .ToList();
                usedCalls = used.Count;
                usedTokens = used.Sum(x => (long)x.EstimatedTokenCount);
            }
            else
            {
                var used = await interactions
                    .Where(x => x.CreatedAtUtc >= monthStart)
                    .GroupBy(_ => 1)
                    .Select(g => new { Calls = g.Count(), Tokens = g.Sum(x => (long)x.EstimatedTokenCount) })
                    .FirstOrDefaultAsync(ct);
                usedCalls = used?.Calls ?? 0;
                usedTokens = used?.Tokens ?? 0;
            }
            if (usedCalls >= entitlements.MonthlyAiCalls)
                return StatusCode(StatusCodes.Status429TooManyRequests, $"Monthly AI limit reached ({entitlements.MonthlyAiCalls} generations). Upgrade your plan or try again next month.");
            if (usedTokens >= entitlements.MonthlyAiTokens)
                return StatusCode(StatusCodes.Status429TooManyRequests, $"Monthly AI cost limit reached ({entitlements.MonthlyAiTokens:N0} estimated tokens). Upgrade your plan or try again next month.");
        }

        try
        {
            var interaction = await _workspace.GenerateAsync(
                user.Id, jobId, user.ProfileCvText ?? string.Empty, ResolveName(user),
                new AiGenerateRequest(request.Module, request.Mode, request.ExtraContext), ResolveProvider(), ct);
            return interaction is null ? NotFound() : Ok(ToDto(interaction));
        }
        catch (ArgumentException ex)
        {
            return BadRequest(ex.Message);
        }
        catch (AiUnavailableException ex)
        {
            return StatusCode(StatusCodes.Status502BadGateway, ex.Message);
        }
    }

    [HttpGet("history")]
    public async Task<ActionResult<IEnumerable<InteractionDto>>> History(int jobId, [FromQuery] string? module, CancellationToken ct)
    {
        var user = await _users.GetUserAsync(User);
        if (user is null) return Unauthorized();
        var history = await _workspace.HistoryAsync(user.Id, jobId, module, ct);
        return Ok(history.Select(ToDto));
    }

    [HttpDelete("history/{id:int}")]
    public async Task<IActionResult> Delete(int jobId, int id, CancellationToken ct)
    {
        var user = await _users.GetUserAsync(User);
        if (user is null) return Unauthorized();
        return await _workspace.DeleteAsync(user.Id, id, ct) ? NoContent() : NotFound();
    }

    private string ResolveProvider() =>
        _config["Ai:Provider"] ?? Environment.GetEnvironmentVariable("AI_PROVIDER") ?? "ai-service";

    private static string ResolveName(ApplicationUser user)
    {
        var name = string.Join(" ", new[] { user.FirstName?.Trim(), user.LastName?.Trim() }.Where(x => !string.IsNullOrWhiteSpace(x)));
        if (string.IsNullOrWhiteSpace(name)) name = user.DisplayName?.Trim();
        if (string.IsNullOrWhiteSpace(name)) name = user.UserName?.Trim();
        return name ?? string.Empty;
    }

    private static InteractionDto ToDto(AiInteraction x) => new(
        x.Id, x.Module, x.Mode, x.Title, x.Provider,
        JsonSerializer.Deserialize<JsonElement>(string.IsNullOrWhiteSpace(x.ResultJson) ? "{}" : x.ResultJson),
        x.InputCharacterCount, x.OutputCharacterCount, x.EstimatedTokenCount, x.CreatedAtUtc);
}
