using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using JobTrackerApi.Data;
using JobTrackerApi.Services;
using JobTrackerApi.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace JobTrackerApi.Controllers;
public sealed partial class ProfileCvController : ControllerBase
{
    private static void AnnotateStructuredCv(StructuredCvProfile profile, string method, double confidence)
    {
        var now = DateTimeOffset.UtcNow;
        profile.Metadata ??= new StructuredCvMetadata();
        profile.Metadata.Fields ??= new Dictionary<string, StructuredCvFieldMetadata>();

        void SetIf(string key, string? value)
        {
            if (string.IsNullOrWhiteSpace(value)) return;
            profile.Metadata.Fields[key] = new StructuredCvFieldMetadata
            {
                Confidence = confidence,
                Method = method,
                SourceSnippet = value.Length > 180 ? value[..180] : value,
                ReviewState = "suggested",
                LastUpdatedAtUtc = now,
            };
        }

        SetIf("contact.fullName", profile.Contact.FullName);
        SetIf("contact.headline", profile.Contact.Headline);
        SetIf("contact.email", profile.Contact.Email);
        SetIf("contact.phone", profile.Contact.Phone);
        SetIf("contact.location", profile.Contact.Location);
        SetIf("contact.website", profile.Contact.Website);
        SetIf("contact.linkedIn", profile.Contact.LinkedIn);
        SetIf("summary", profile.Summary.FirstOrDefault());
        SetIf("skills", profile.Skills.FirstOrDefault());
        SetIf("languages", profile.Languages.FirstOrDefault()?.Name);
        SetIf("interests", profile.Interests.FirstOrDefault());
        SetIf("jobs", profile.Jobs.FirstOrDefault()?.Title ?? profile.Jobs.FirstOrDefault()?.Company);
        SetIf("education", profile.Education.FirstOrDefault()?.Qualification ?? profile.Education.FirstOrDefault()?.Institution);
    }

    private async Task<StructuredCvProfile?> TryExtractStructuredCvAsync(string text, CancellationToken cancellationToken)
    {
        var structuredJson = await _aiService.SummarizeSectionAsync(
            "Extract this CV into structured JSON. Return only valid JSON with this exact top-level shape: { \"version\": \"1\", \"contact\": { \"fullName\": string|null, \"headline\": string|null, \"email\": string|null, \"phone\": string|null, \"location\": string|null, \"website\": string|null, \"linkedin\": string|null }, \"summary\": string[], \"jobs\": [{ \"title\": string|null, \"company\": string|null, \"location\": string|null, \"start\": string|null, \"end\": string|null, \"isCurrent\": boolean, \"bullets\": string[], \"skills\": string[] }], \"education\": [{ \"qualification\": string|null, \"qualificationLevel\": \"Secondary\"|\"Diploma/Certificate\"|\"Bachelor\"|\"Master\"|\"PhD\"|\"Other\"|null, \"institution\": string|null, \"location\": string|null, \"start\": string|null, \"end\": string|null, \"details\": string[] }], \"certifications\": [{ \"name\": string|null, \"issuer\": string|null, \"location\": string|null, \"date\": string|null, \"details\": string[] }], \"projects\": [{ \"name\": string|null, \"role\": string|null, \"location\": string|null, \"start\": string|null, \"end\": string|null, \"bullets\": string[], \"skills\": string[] }], \"skills\": string[], \"languages\": [{ \"name\": string|null, \"level\": string|null, \"notes\": string|null }], \"interests\": string[], \"otherSections\": [{ \"title\": string|null, \"items\": string[] }] }. Preserve facts only. Do not invent anything. If a field is unknown, use null or an empty array. Keep wording close to the source. Profile location should only be the candidate's current/home location. Education location must be the institution location. Work location must be employer/job location. Never place skill lists such as Python or Ruby into location fields. Preserve the original qualification text in education. Set qualificationLevel to the normalized enum when you can infer it, otherwise null. Put unmatched content in otherSections.",
            text,
            3200,
            900);

        if (string.IsNullOrWhiteSpace(structuredJson)) return null;
        var extracted = ExtractJsonObject(structuredJson);
        if (string.IsNullOrWhiteSpace(extracted)) return null;

        var parsed = StructuredCvProfileJson.Deserialize(extracted);
        if (!IsMeaningfullyStructured(parsed)) return null;

        AnnotateStructuredCv(parsed, "llm", 0.82);
        return parsed;
    }

    private static bool IsMeaningfullyStructured(StructuredCvProfile profile)
    {
        return !string.IsNullOrWhiteSpace(profile.Contact.FullName)
            || profile.Summary.Count > 0
            || profile.Jobs.Count > 0
            || profile.Education.Count > 0
            || profile.Skills.Count > 0
            || profile.Languages.Count > 0
            || profile.Interests.Count > 0
            || profile.OtherSections.Count > 0;
    }

    private static string? ExtractJsonObject(string raw)
    {
        var trimmed = raw.Trim();
        if (trimmed.StartsWith("```", StringComparison.Ordinal))
        {
            trimmed = Regex.Replace(trimmed, "^```(?:json)?\\s*|\\s*```$", string.Empty, RegexOptions.IgnoreCase);
        }

        var start = trimmed.IndexOf('{');
        var end = trimmed.LastIndexOf('}');
        if (start < 0 || end <= start) return null;
        return trimmed[start..(end + 1)];
    }

    private static string? GuessFullName(string source)
    {
        var normalized = source.Replace("\r\n", "\n");
        foreach (var line in normalized.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Take(6))
        {
            var cleaned = line.Trim().TrimStart('#').Trim();
            cleaned = Regex.Replace(cleaned, @"(?<=[a-z])(?=[A-Z])", " ");
            if (cleaned.Length < 4 || cleaned.Length > 80) continue;
            if (cleaned.Contains('@') || Regex.IsMatch(cleaned, @"\d")) continue;

            var nameMatch = Regex.Match(cleaned, @"^(?<name>[A-Z][A-Za-z'`.-]+(?:\s+[A-Z][A-Za-z'`.-]+){1,3})(?:\s+(?:Real Estate Agent|Store Manager|Web Developer|Developer|Engineer|Consultant|Specialist|Analyst).*)?$", RegexOptions.IgnoreCase);
            if (nameMatch.Success)
            {
                return nameMatch.Groups["name"].Value.Trim();
            }

            if (!Regex.IsMatch(cleaned, @"^[A-Z][A-Za-z'`.-]+(?:\s+[A-Z][A-Za-z'`.-]+){1,4}$")) continue;
            return cleaned;
        }

        return null;
    }

    private static string? GuessFullNameFromEmail(string? email)
    {
        if (string.IsNullOrWhiteSpace(email) || !email.Contains('@')) return null;
        var localPart = email[..email.IndexOf('@')].Trim();
        if (string.IsNullOrWhiteSpace(localPart)) return null;
        var parts = Regex.Split(localPart, @"[._-]+")
            .Select(part => part.Trim())
            .Where(part => part.Length > 0)
            .Select(part => char.ToUpperInvariant(part[0]) + part[1..].ToLowerInvariant())
            .ToList();
        return parts.Count >= 2 ? string.Join(" ", parts) : null;
    }

    private static string NormalizeTextForStructuredParsing(string source)
    {
        if (string.IsNullOrWhiteSpace(source)) return string.Empty;

        var text = source.Replace("\r\n", "\n").Trim();
        if (!LooksLikeFlattenedCvExtraction(text)) return text;

        text = Regex.Replace(text, @"\b([A-Z](?:\s+[A-Z]){2,})\b", match =>
        {
            var collapsed = Regex.Replace(match.Value, @"\s+", string.Empty);
            foreach (var alias in SectionAliases)
            {
                var aliasLettersOnly = Regex.Replace(alias.Key, @"[^A-Za-z]", string.Empty);
                if (collapsed.Equals(aliasLettersOnly, StringComparison.OrdinalIgnoreCase))
                {
                    return $"\n\n## {alias.Value}\n";
                }
            }

            return match.Value;
        });

        foreach (var alias in SectionAliases.OrderByDescending(pair => pair.Key.Length))
        {
            text = Regex.Replace(
                text,
                $@"(?<!#)\b{Regex.Escape(alias.Key)}\b",
                $"\n\n## {alias.Value}\n",
                RegexOptions.IgnoreCase);
        }

        text = Regex.Replace(text, @"\s+\+\s+", "\n+ ");
        text = Regex.Replace(text, @"\s*([•●▪◦])\s*", "\n- ");
        text = Regex.Replace(text, @"\s+(\d{4}\s*[-–]\s*(?:\d{4}|Present|Current))\b", "\n$1\n", RegexOptions.IgnoreCase);
        text = Regex.Replace(text, @"\n{3,}", "\n\n");

        return text.Trim();
    }

    private static StructuredCvProfile BuildHeuristicStructuredCv(string parseSource, string rawSource)
    {
        var profile = new StructuredCvProfile();
        var normalized = parseSource.Replace("\r\n", "\n").Trim();

        profile.Contact.Email = NullIfWhitespace(Regex.Match(rawSource, @"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}", RegexOptions.IgnoreCase).Value);
        profile.Contact.Phone = NormalizeDetectedPhone(Regex.Match(rawSource, @"(?<!\w)(?:\+?\d[\d\s().-]{6,}\d)", RegexOptions.IgnoreCase).Value);
        profile.Contact.Website = ExtractPreferredWebsite(rawSource, profile.Contact.Email);
        profile.Contact.LinkedIn = NullIfWhitespace(Regex.Match(rawSource, @"(?:linkedin(?:\.com)?/[A-Z0-9._~:/?#\[\]@!$&'()*+,;=-]+)", RegexOptions.IgnoreCase).Value);
        profile.Contact.FullName = GuessFullName(rawSource) ?? GuessFullNameFromEmail(profile.Contact.Email);

        var sections = ParseSections(normalized);
        var contactSection = sections.FirstOrDefault(section => section.Name == "Contact");
        if (!string.IsNullOrWhiteSpace(contactSection.Content))
        {
            var contactFallback = StructuredCvProfileJson.FromSections(new[] { new StructuredCvSection { Name = "Contact", Content = contactSection.Content } });
            profile.Contact.Location = PreferDetectedLocation(contactSection.Content, contactFallback.Contact.Location, profile.Contact.FullName);
            profile.Contact.Headline ??= CleanHeadline(contactFallback.Contact.Headline, profile.Contact.FullName);
        }
        else
        {
            profile.Contact.Location = PreferDetectedLocation(rawSource, NullIfWhitespace(Regex.Match(rawSource, @"\b[A-Z][a-z]+(?:[\s-][A-Z][a-z]+)*(?:,\s*[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*){1,2}\b").Value), profile.Contact.FullName);
        }

        if (string.IsNullOrWhiteSpace(profile.Contact.Location))
        {
            var firstTenLines = normalized.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Take(10).ToList();
            profile.Contact.Location = firstTenLines.FirstOrDefault(line =>
                !line.Contains('@')
                && !Regex.IsMatch(line, @"https?://|www\.", RegexOptions.IgnoreCase)
                && Regex.IsMatch(line, @"^[A-Z][A-Za-z.' -]+(?:,\s*[A-Z][A-Za-z.' -]+)?$")
                && !line.Contains("Skills", StringComparison.OrdinalIgnoreCase)
                && !line.Contains("Summary", StringComparison.OrdinalIgnoreCase)
                && !line.Contains("Developer", StringComparison.OrdinalIgnoreCase)
                && !line.Contains("Agent", StringComparison.OrdinalIgnoreCase)
                && !string.Equals(line, profile.Contact.FullName, StringComparison.OrdinalIgnoreCase));
        }

        if (!string.IsNullOrWhiteSpace(profile.Contact.Location))
        {
            profile.Contact.Location = Regex.Replace(profile.Contact.Location, @"\bSkills\b.*$", string.Empty, RegexOptions.IgnoreCase).Trim(' ', ',');
        }

        var summarySection = sections.FirstOrDefault(section => section.Name == "Professional Summary");
        var flattenedSummary = Regex.Match(
            rawSource,
            @"(?:A\s+B\s+O\s+U\s+T\s+M\s+E|P\s+R\s+O\s+F\s+I\s+L\s+E|S\s+U\s+M\s+M\s+A\s+R\s+Y)\s*(?<body>.*?)(?=(?:I\s+N\s+T\s+E\s+R\s+E\s+S\s+T\s+S|E\s+X\s+P\s+E\s+R\s+I\s+E\s+N\s+C\s+E|E\s+D\s+U\s+C\s+A\s+T\s+I\s+O\s+N|C\s+O\s+N\s+T\s+A\s+C\s+T|$))",
            RegexOptions.IgnoreCase | RegexOptions.Singleline);
        if (flattenedSummary.Success)
        {
            profile.Summary = SplitSentences(flattenedSummary.Groups["body"].Value, 5)
                .Where(item => !Regex.IsMatch(item, @"^:?\s*https?://", RegexOptions.IgnoreCase))
                .ToList();
        }
        else if (!string.IsNullOrWhiteSpace(summarySection.Content))
        {
            profile.Summary = SplitSentences(summarySection.Content, 5)
                .Where(item => !Regex.IsMatch(item, @"^:?\s*https?://", RegexOptions.IgnoreCase))
                .ToList();
        }

        var interestsSection = sections.FirstOrDefault(section => section.Name == "Interests");
        if (!string.IsNullOrWhiteSpace(interestsSection.Content))
        {
            profile.Interests = SplitListLike(interestsSection.Content);
        }
        else
        {
            var flattenedInterests = Regex.Match(
                rawSource,
                @"I\s+N\s+T\s+E\s+R\s+E\s+S\s+T\s+S\s*(?<body>.*?)(?=(?:E\s+X\s+P\s+E\s+R\s+I\s+E\s+N\s+C\s+E|C\s+O\s+N\s+T\s+A\s+C\s+T|E\s+D\s+U\s+C\s+A\s+T\s+I\s+O\s+N|$))",
                RegexOptions.IgnoreCase | RegexOptions.Singleline);
            if (flattenedInterests.Success)
            {
                profile.Interests = SplitSentences(flattenedInterests.Groups["body"].Value, 4);
            }
        }

        var languagesSection = sections.FirstOrDefault(section => section.Name == "Languages");
        if (!string.IsNullOrWhiteSpace(languagesSection.Content))
        {
            profile.Languages = ParseLanguagesHeuristically(languagesSection.Content);
        }
        else
        {
            profile.Languages = ParseLanguagesHeuristically(rawSource);
        }

        var skills = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        var skillSections = sections.Where(section => section.Name == "Skills").ToList();
        var skillsSource = string.Join("\n", skillSections.Select(section => section.Content));
        if (string.IsNullOrWhiteSpace(skillsSource)) skillsSource = rawSource;
        foreach (var skill in ExtractSkillsHeuristically(skillsSource))
        {
            skills.Add(skill);
        }
        // Once a heading has positively bounded a Skills section, its list items are stronger
        // evidence than the conservative whole-document vocabulary. Preserve domain-specific items
        // without mining arbitrary prose as skills.
        if (skillSections.Count > 0)
        {
            foreach (var item in SplitListLike(skillsSource))
            {
                var cleaned = CleanSkillGroupPrefix(item);
                if (cleaned.Length is >= 2 and <= 80 && cleaned.Any(char.IsLetter)) skills.Add(cleaned);
            }
        }
        profile.Skills = skills.Select(CleanSkillGroupPrefix)
            .Where(skill => skill.Length > 0)
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .ToList();

        var educationSection = sections.FirstOrDefault(section => section.Name == "Education");
        if (!string.IsNullOrWhiteSpace(educationSection.Content))
        {
            profile.Education = ParseEducationHeuristically(educationSection.Content);
        }

        var certificationsSection = sections.FirstOrDefault(section => section.Name == "Certifications");
        if (!string.IsNullOrWhiteSpace(certificationsSection.Content))
        {
            profile.Certifications = StructuredCvProfileJson.FromSections(new[] { new StructuredCvSection { Name = "Certifications", Content = certificationsSection.Content } }).Certifications;
        }

        var projectsSection = sections.FirstOrDefault(section => section.Name == "Projects");
        if (!string.IsNullOrWhiteSpace(projectsSection.Content))
        {
            profile.Projects = StructuredCvProfileJson.FromSections(new[] { new StructuredCvSection { Name = "Projects", Content = projectsSection.Content } }).Projects;
        }

        var experienceSection = sections.FirstOrDefault(section => section.Name == "Work Experience");
        if (!string.IsNullOrWhiteSpace(experienceSection.Content))
        {
            profile.Jobs = ParseJobsHeuristically(experienceSection.Content);
        }
        else if (profile.Jobs.Count == 0)
        {
            profile.Jobs = ParseJobsHeuristically(normalized);
        }

        var handledSections = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
        {
            "General", "Contact", "Professional Summary", "Skills", "Work Experience", "Education",
            "Projects", "Certifications", "Languages", "Interests", "Awards", "Publications",
            "Organisations", "References", "Selected Achievements",
        };
        foreach (var section in sections.Where(section => !handledSections.Contains(section.Name)))
        {
            var items = SplitListLike(section.Content);
            if (items.Count == 0 && !string.IsNullOrWhiteSpace(section.Content)) items.Add(section.Content.Trim());
            if (items.Count > 0 && !profile.OtherSections.Any(existing => string.Equals(existing.Title, section.Name, StringComparison.OrdinalIgnoreCase)))
                profile.OtherSections.Add(new StructuredCvOtherSection { Title = section.Name, Items = items });
        }

        if (profile.OtherSections.Count == 0 && sections.Any(section => section.Name == "General"))
        {
            var general = sections.First(section => section.Name == "General");
            if (!string.IsNullOrWhiteSpace(general.Content) && profile.Summary.Count == 0)
            {
                profile.Summary = SplitSentences(general.Content, 3);
            }
        }

        return StructuredCvProfileJson.Normalize(profile);
    }

    private static List<string> SplitSentences(string content, int limit)
    {
        return Regex.Split(content.Replace("\r\n", " "), @"(?<=[.!?])\s+")
            .Select(value => value.Trim())
            .Where(value => value.Length > 20)
            .Take(limit)
            .ToList();
    }

    private static readonly string[] ConservativeSkillHints =
    {
        "C#", ".NET", "ASP.NET", "SQL", "JavaScript", "TypeScript", "Python", "Ruby on Rails", "Ruby", "React", "Azure", "Azure DevOps", "GitHub", "CI/CD", "HTML5", "CSS", "MySQL", "PHP OOP", "Project management", "Revenue generation", "Business development", "Effective marketing", "Organisational capacity", "Operability and commitment", "Attention to Detail", "Property Valuation", "Retail Market Analysis", "Client Relationship Management", "Digital Marketing"
    };

    private static List<string> SplitListLike(string content)
    {
        return content
            .Replace("\r\n", "\n")
            .Split(new[] { '\n', ',', ';', '•', '●' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
            .SelectMany(item => item.Contains("  ", StringComparison.Ordinal) ? Regex.Split(item, @"\s{2,}") : new[] { item })
            .Select(item => item.Trim().TrimStart('-', '•', '*', ' '))
            .Where(item => item.Length > 1)
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .ToList();
    }

    private static IEnumerable<string> ExtractConservativeSkills(string content)
    {
        foreach (var skill in ConservativeSkillHints)
        {
            if (Regex.IsMatch(content, $@"(?<![A-Za-z0-9]){Regex.Escape(skill)}(?![A-Za-z0-9])", RegexOptions.IgnoreCase))
            {
                yield return skill;
            }
        }
    }

    private static List<string> ExtractSkillsFromBullets(IEnumerable<string> bullets)
    {
        return ExtractConservativeSkills(string.Join("\n", bullets))
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .ToList();
    }

    private static IEnumerable<string> ExtractSkillsHeuristically(string content)
    {
        var yielded = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

        foreach (var skill in ExtractConservativeSkills(content))
        {
            if (yielded.Add(skill)) yield return skill;
        }

        var highlightsMatch = Regex.Match(content, @"(?:Highlights|Core Skills|Skills|Technical Skills|Skill Highlights|Competencies)\s*(?<body>.*?)(?=(?:Experience|Education|Languages|Interests|Projects|Certifications|$))", RegexOptions.IgnoreCase | RegexOptions.Singleline);
        if (highlightsMatch.Success)
        {
            foreach (var item in SplitListLike(highlightsMatch.Groups["body"].Value))
            {
                var trimmed = item.Trim();
                if (trimmed.Length >= 3 && trimmed.Length <= 80 && trimmed.Count(char.IsLetter) >= 3)
                {
                    if (yielded.Add(trimmed)) yield return trimmed;
                }
            }
        }
    }

    private static string? NormalizeDetectedPhone(string? value)
    {
        var trimmed = NullIfWhitespace(value);
        if (trimmed is null) return null;

        var digits = trimmed.Count(char.IsDigit);
        if (digits < 7) return null;

        var looksLikeRawCoordinates = trimmed.Contains(" -") && digits > 18 && !trimmed.Contains('+') && !trimmed.Contains('(');
        if (looksLikeRawCoordinates) return null;

        return trimmed;
    }

    private static string? NormalizeDetectedWebsite(string? value, string? email)
    {
        var trimmed = NullIfWhitespace(value);
        if (trimmed is null) return null;
        if (!trimmed.Contains('.', StringComparison.Ordinal)) return null;
        if (trimmed.Contains('@')) return null;
        if (trimmed.Equals("gmail.com", StringComparison.OrdinalIgnoreCase)) return null;

        var candidate = trimmed.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? trimmed : $"https://{trimmed}";
        if (!Uri.TryCreate(candidate, UriKind.Absolute, out var uri)) return null;
        if (string.IsNullOrWhiteSpace(uri.Host) || !uri.Host.Contains('.', StringComparison.Ordinal)) return null;

        return trimmed.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? trimmed : uri.Host;
    }

    private static string? ExtractPreferredWebsite(string rawSource, string? email)
    {
        foreach (Match match in Regex.Matches(rawSource, @"\b(?:https?://)?(?:www\.)?[A-Z0-9.-]+\.[A-Z]{2,}(?:/[A-Z0-9._~:/?#\[\]@!$&'()*+,;=-]*)?", RegexOptions.IgnoreCase))
        {
            if ((match.Index > 0 && rawSource[match.Index - 1] == '@')
                || (match.Index + match.Length < rawSource.Length && rawSource[match.Index + match.Length] == '@')) continue;
            var candidate = NormalizeDetectedWebsite(match.Value, email);
            if (candidate is null) continue;
            if (candidate.Contains("linkedin.com", StringComparison.OrdinalIgnoreCase)) continue;
            return candidate;
        }

        return null;
    }

    private static string? PreferDetectedLocation(string source, string? fallback, string? fullName = null)
    {
        var normalizedFallback = NullIfWhitespace(fallback);
        if (normalizedFallback is not null)
        {
            normalizedFallback = Regex.Replace(normalizedFallback, @",?\s*(Hobbies|Education)\b.*$", string.Empty, RegexOptions.IgnoreCase).Trim(' ', ',');
        }

        if (IsPlausibleLocationValue(normalizedFallback, fullName))
        {
            return normalizedFallback;
        }

        var lines = source.Replace("\r\n", "\n").Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
        foreach (var rawLine in lines.Take(10))
        {
            foreach (var segment in Regex.Split(rawLine, @"\s*(?:[•·|]|\s{2,})\s*").Where(value => !string.IsNullOrWhiteSpace(value)))
            {
                var line = Regex.Replace(segment, @",?\s*(Hobbies|Education)\b.*$", string.Empty, RegexOptions.IgnoreCase).Trim(' ', ',');
                if (!IsPlausibleLocationValue(line, fullName)) continue;
                return line;
            }
        }

        return IsPlausibleLocationValue(normalizedFallback, fullName) ? normalizedFallback : null;
    }

    private static bool IsPlausibleLocationValue(string? value, string? fullName)
    {
        var candidate = NullIfWhitespace(value);
        if (candidate is null) return false;
        if (CanonicalizeSectionHeading(candidate) is not null) return false;
        if (LooksLikeRoleOrHeadline(candidate)) return false;
        if (!string.IsNullOrWhiteSpace(fullName))
        {
            if (candidate.Equals(fullName, StringComparison.OrdinalIgnoreCase)) return false;
            if (candidate.StartsWith(fullName + " ", StringComparison.OrdinalIgnoreCase)) return false;
        }

        if (candidate.Contains("Education", StringComparison.OrdinalIgnoreCase)
            || candidate.Contains("Hobbies", StringComparison.OrdinalIgnoreCase)
            || candidate.Contains("Skills", StringComparison.OrdinalIgnoreCase)
            || candidate.Contains("Summary", StringComparison.OrdinalIgnoreCase)) return false;
        if (candidate.Contains('@') || Regex.IsMatch(candidate, @"https?://|www\.", RegexOptions.IgnoreCase)) return false;
        if (candidate.Count(char.IsDigit) >= 5) return false;
        if (Regex.IsMatch(candidate, @"^\d+\s+.+")) return true;

        var normalized = Regex.Replace(candidate, @"\s+", " ").Trim(' ', ',');
        if (normalized.Length > 80) return false;

        if (Regex.IsMatch(normalized, @"^\p{Lu}[\p{L}.' -]+,\s*\p{Lu}[\p{L}.' -]+(?:,\s*\p{Lu}[\p{L}.' -]+)?$")) return true;
        if (Regex.IsMatch(normalized, @"^\p{Lu}[\p{L}.' -]+(?:\s+\p{Lu}[\p{L}.' -]+){0,2}$") && !LooksLikeRoleOrHeadline(normalized)) return true;

        return false;
    }

    private static bool LooksLikeRoleOrHeadline(string value)
    {
        return Regex.IsMatch(value, @"\b(real estate agent|developer|development|engineer|manager|consultant|specialist|analyst|designer|technician|administrator|architect|director|coordinator|assistant|lead|owner|founder|recruiter|teacher|writer|producer|officer|supervisor|sales|competencies)\b", RegexOptions.IgnoreCase);
    }

    private static bool LooksLikePersonName(string value)
    {
        return Regex.IsMatch(value, @"^[A-Z][A-Za-z'`.-]+(?:\s+[A-Z][A-Za-z'`.-]+){1,3}$")
            && !LooksLikeRoleOrHeadline(value);
    }

    private static bool ArePlausibleJobs(List<StructuredCvJob>? jobs, string? fullName)
    {
        if (jobs is null || jobs.Count == 0) return false;
        return jobs.Any(job => IsPlausibleJob(job, fullName));
    }

    private static int ScoreJobs(List<StructuredCvJob>? jobs, string? fullName)
    {
        if (jobs is null || jobs.Count == 0) return 0;
        var first = jobs[0];
        var score = 0;
        if (IsPlausibleJob(first, fullName)) score += 5;
        if (!string.IsNullOrWhiteSpace(first.Title) && LooksLikeRoleOrHeadline(first.Title)) score += 4;
        if (!string.IsNullOrWhiteSpace(first.Company)) score += 2;
        if (!string.IsNullOrWhiteSpace(first.Start) || !string.IsNullOrWhiteSpace(first.End)) score += 2;
        if (first.Bullets.Count > 0) score += 2;
        score += Math.Min(jobs.Count, 3);
        return score;
    }

    private static bool IsPlausibleJob(StructuredCvJob? job, string? fullName)
    {
        if (job is null) return false;
        var title = NullIfWhitespace(job.Title);
        var company = NullIfWhitespace(job.Company);
        var location = NullIfWhitespace(job.Location);
        var hasEvidence = !string.IsNullOrWhiteSpace(company)
            || !string.IsNullOrWhiteSpace(location)
            || !string.IsNullOrWhiteSpace(job.Start)
            || !string.IsNullOrWhiteSpace(job.End)
            || job.Bullets.Count > 0;

        if (title is null) return hasEvidence;
        if (!string.IsNullOrWhiteSpace(fullName) && title.Equals(fullName, StringComparison.OrdinalIgnoreCase)) return false;
        if (LooksLikePersonName(title)) return false;
        if (title.Contains('@') || Regex.IsMatch(title, @"https?://|www\.", RegexOptions.IgnoreCase)) return false;
        if (Regex.IsMatch(title, @"^(?:\d{2}/\d{4}|\d{4})\s*(?:[-–]|to)\s*(?:\d{2}/\d{4}|\d{4}|Present|Current)$", RegexOptions.IgnoreCase)) return false;
        if (!hasEvidence && !LooksLikeRoleOrHeadline(title)) return false;
        return true;
    }

    private static string? CleanHeadline(string? value, string? fullName)
    {
        var trimmed = NullIfWhitespace(value);
        if (trimmed is null) return null;
        if (!string.IsNullOrWhiteSpace(fullName) && trimmed.Equals(fullName, StringComparison.OrdinalIgnoreCase)) return null;
        if (trimmed.Contains('@') || trimmed.Count(char.IsDigit) > 3) return null;
        return trimmed;
    }

    private static List<StructuredCvLanguage> ParseLanguagesHeuristically(string content)
    {
        var languages = new List<StructuredCvLanguage>();
        foreach (var line in content.Replace("\r\n", "\n").Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
        {
            var paired = Regex.Split(line, @"\s*(?:[•·|]|[—–](?!\d))\s*")
                .Select(item => item.Trim())
                .Where(item => item.Length > 0)
                .ToList();
            if (paired.Count < 2) continue;

            for (var index = 0; index + 1 < paired.Count; index += 2)
            {
                var level = HumanLanguageCatalog.ExtractLevel(paired[index + 1]);
                if (level is null) continue;
                foreach (var name in HumanLanguageCatalog.ExtractLanguageNames(paired[index]))
                    languages.Add(new StructuredCvLanguage { Name = name, Level = level });
            }
        }

        var candidates = Regex.Split(content.Replace("\r\n", "\n"), @"[\n,;]+|(?<=[.!?])\s+")
            .Select(item => item.Trim())
            .Where(item => item.Length > 1);

        foreach (var candidate in candidates)
        {
            var level = HumanLanguageCatalog.ExtractLevel(candidate);
            if (level is null) continue;

            foreach (var name in HumanLanguageCatalog.ExtractLanguageNames(candidate))
            {
                languages.Add(new StructuredCvLanguage { Name = name, Level = level });
            }
        }

        return languages
            .GroupBy(language => language.Name, StringComparer.OrdinalIgnoreCase)
            .Select(group => group.First())
            .ToList();
    }

    private static List<StructuredCvEducation> ParseEducationHeuristically(string content)
    {
        var normalized = content.Replace("\r\n", "\n").Trim();
        var direct = StructuredCvProfileJson.FromSections(new[] { new StructuredCvSection { Name = "Education", Content = normalized } }).Education;
        if (direct.Count == 1 && direct.Any(item => !string.IsNullOrWhiteSpace(item.Institution)
            || !string.IsNullOrWhiteSpace(item.Start) || !string.IsNullOrWhiteSpace(item.End)))
        {
            return direct;
        }
        var blocks = Regex.Split(normalized, @"\n\s*\n|(?=###\s+)|(?=(?:Bachelor|Master|Doctor|Associate|Diploma|Certificate|BSc|BA|MSc|MA|PhD)\b)", RegexOptions.IgnoreCase)
            .Select(block => block.Trim())
            .Where(block => block.Length > 0)
            .ToList();

        var items = new List<StructuredCvEducation>();
        foreach (var block in blocks)
        {
            var candidate = StructuredCvProfileJson.FromSections(new[] { new StructuredCvSection { Name = "Education", Content = block } }).Education;
            if (candidate.Count > 0)
            {
                items.AddRange(candidate);
                continue;
            }

            var lines = block.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
            if (lines.Count == 0) continue;

            var dateMatch = Regex.Match(block, @"\b(\d{4})\s*[-–]\s*(\d{4}|Present|Current)\b", RegexOptions.IgnoreCase);
            var institutionLine = lines.FirstOrDefault(line => line.StartsWith("+ ", StringComparison.Ordinal))?.TrimStart('+', ' ');
            var qualificationLine = lines.FirstOrDefault(line => !line.StartsWith("+ ", StringComparison.Ordinal) && !Regex.IsMatch(line, @"^\d{4}\s*[-–]"));
            if (qualificationLine is null && lines.Count > 0) qualificationLine = lines[0];

            if (qualificationLine is null && institutionLine is null) continue;
            items.Add(new StructuredCvEducation
            {
                Qualification = TitleCasePreservingAcronyms(qualificationLine),
                QualificationLevel = InferQualificationLevel(qualificationLine),
                Institution = TitleCasePreservingAcronyms(institutionLine),
                Start = dateMatch.Success ? dateMatch.Groups[1].Value : null,
                End = dateMatch.Success ? dateMatch.Groups[2].Value : null,
                Details = lines.Where(line => line.StartsWith("- ", StringComparison.Ordinal)).Select(line => line[2..].Trim()).ToList(),
            });
        }

        return items;
    }

    private static List<StructuredCvJob> ParseJobsHeuristically(string content)
    {
        var normalized = content.Replace("\r\n", "\n").Trim();
        var structured = StructuredCvProfileJson.FromSections(new[] { new StructuredCvSection { Name = "Work Experience", Content = normalized } }).Jobs;
        var earlierRoles = ParseEarlierRoles(normalized);
        foreach (var role in earlierRoles)
        {
            if (!structured.Any(job => string.Equals(job.Title, role.Title, StringComparison.OrdinalIgnoreCase)
                && string.Equals(job.Company, role.Company, StringComparison.OrdinalIgnoreCase)))
            {
                structured.Add(role);
            }
        }
        if (ArePlausibleJobs(structured, null))
        {
            return structured;
        }

        var simpleLines = normalized.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
        var inlineDateIndex = Array.FindIndex(simpleLines, line => Regex.IsMatch(line, @".+\d{2}/\d{4}\s+to\s+\d{2}/\d{4}", RegexOptions.IgnoreCase) || Regex.IsMatch(line, @".+\d{4}\s*(?:[-–]|to)\s*(?:\d{4}|Present|Current)", RegexOptions.IgnoreCase));
        if (inlineDateIndex >= 0)
        {
            var titleLine = Regex.Replace(simpleLines[inlineDateIndex], @"\s*[-–]?\s*\d{2}/\d{4}\s+to\s+\d{2}/\d{4}.*$", string.Empty, RegexOptions.IgnoreCase);
            titleLine = Regex.Replace(titleLine, @"\s*[-–]?\s*\d{4}\s*[-–]\s*(?:\d{4}|Present|Current).*$", string.Empty, RegexOptions.IgnoreCase).Trim();
            var companyOrLocation = inlineDateIndex + 1 < simpleLines.Length ? simpleLines[inlineDateIndex + 1] : null;
            var datesMatch = Regex.Match(simpleLines[inlineDateIndex], @"(\d{2}/\d{4}|\d{4})\s*(?:to|[-–])\s*(\d{2}/\d{4}|\d{4}|Present|Current)", RegexOptions.IgnoreCase);
            var bullets = simpleLines.Skip(inlineDateIndex + 2).Where(line => line.Length > 12).ToList();
            if (!string.IsNullOrWhiteSpace(titleLine))
            {
                return new List<StructuredCvJob>
                {
                    new StructuredCvJob
                    {
                        Title = titleLine,
                        Company = companyOrLocation,
                        Start = datesMatch.Success ? datesMatch.Groups[1].Value : null,
                        End = datesMatch.Success ? datesMatch.Groups[2].Value : null,
                        IsCurrent = datesMatch.Success && (string.Equals(datesMatch.Groups[2].Value, "Present", StringComparison.OrdinalIgnoreCase) || string.Equals(datesMatch.Groups[2].Value, "Current", StringComparison.OrdinalIgnoreCase)),
                        Bullets = bullets,
                        Skills = ExtractSkillsFromBullets(bullets),
                    }
                };
            }
        }

        var dateIndex = Array.FindIndex(simpleLines, line => Regex.IsMatch(line, @"(?:\d{2}/\d{4}|\d{4})\s*(?:[-–]|to)\s*(?:\d{2}/\d{4}|\d{4}|Present|Current)", RegexOptions.IgnoreCase));
        if (dateIndex >= 0)
        {
            if (dateIndex + 2 < simpleLines.Length && LooksLikeRoleOrHeadline(simpleLines[dateIndex + 1]))
            {
                var datesLine = simpleLines[dateIndex];
                var titleLine = simpleLines[dateIndex + 1];
                var companyLine = simpleLines[dateIndex + 2];
                var bullets = SplitSentences(string.Join(" ", simpleLines.Skip(dateIndex + 3)), 6);
                var parts = Regex.Split(datesLine, @"\s*[-–]\s*");
                return new List<StructuredCvJob>
                {
                    new StructuredCvJob
                    {
                        Title = titleLine,
                        Company = companyLine,
                        Start = parts.FirstOrDefault(),
                        End = parts.Skip(1).FirstOrDefault(),
                        IsCurrent = string.Equals(parts.Skip(1).FirstOrDefault(), "Present", StringComparison.OrdinalIgnoreCase) || string.Equals(parts.Skip(1).FirstOrDefault(), "Current", StringComparison.OrdinalIgnoreCase),
                        Bullets = bullets,
                        Skills = ExtractSkillsFromBullets(bullets),
                    }
                };
            }

            if (dateIndex >= 2)
            {
                var titleLine = simpleLines[dateIndex - 2];
                var locationLine = simpleLines[dateIndex - 1];
                var datesLine = simpleLines[dateIndex];
                var bullets = simpleLines.Skip(dateIndex + 1).Where(line => line.Length > 12).ToList();
                var parts = Regex.Split(datesLine, @"\s*[-–]\s*");
                return new List<StructuredCvJob>
                {
                    new StructuredCvJob
                    {
                        Title = titleLine,
                        Location = locationLine,
                        Start = parts.FirstOrDefault(),
                        End = parts.Skip(1).FirstOrDefault(),
                        IsCurrent = string.Equals(parts.Skip(1).FirstOrDefault(), "Present", StringComparison.OrdinalIgnoreCase) || string.Equals(parts.Skip(1).FirstOrDefault(), "Current", StringComparison.OrdinalIgnoreCase),
                        Bullets = bullets,
                        Skills = ExtractSkillsFromBullets(bullets),
                    }
                };
            }
        }

        var pattern = new Regex(@"(?<title>[A-Z][A-Z\s/&-]{3,})\s*\n(?<dates>\d{4}\s*[-–]\s*(?:\d{4}|Present|Current))(?<body>.*?)(?=(?:\n[A-Z][A-Z\s/&-]{3,}\s*\n\d{4}\s*[-–]\s*(?:\d{4}|Present|Current))|\z)", RegexOptions.Singleline);
        var jobs = new List<StructuredCvJob>();

        foreach (Match match in pattern.Matches(normalized))
        {
            var body = match.Groups["body"].Value.Trim();
            var employer = NullIfWhitespace(Regex.Match(body, @"\+\s*([^\n]+)").Groups[1].Value);
            var dates = Regex.Split(match.Groups["dates"].Value, @"\s*[-–]\s*");
            var bullets = SplitSentences(Regex.Replace(body, @"\+\s*[^\n]+", string.Empty), 6);

            jobs.Add(new StructuredCvJob
            {
                Title = TitleCasePreservingAcronyms(match.Groups["title"].Value),
                Company = employer,
                Start = NullIfWhitespace(dates.FirstOrDefault()),
                End = NullIfWhitespace(dates.Skip(1).FirstOrDefault()),
                IsCurrent = string.Equals(dates.Skip(1).FirstOrDefault(), "present", StringComparison.OrdinalIgnoreCase) || string.Equals(dates.Skip(1).FirstOrDefault(), "current", StringComparison.OrdinalIgnoreCase),
                Bullets = bullets,
                Skills = ExtractSkillsFromBullets(bullets),
            });
        }

        return jobs;
    }

    private static List<StructuredCvJob> ParseEarlierRoles(string content)
    {
        var heading = Regex.Match(content, @"(?im)^\s*(?:[-*]\s*)?Earlier roles(?:\s*\(part[- ]?time\))?\s*:?\s*$");
        if (!heading.Success) return new List<StructuredCvJob>();

        var roles = new List<StructuredCvJob>();
        foreach (var rawLine in content[(heading.Index + heading.Length)..].Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
        {
            if (rawLine.StartsWith('#')) break;
            var line = rawLine.Trim().TrimStart('-', '*', '•', ' ');
            var dates = Regex.Match(line, @"(?<start>\d{4})\s*[-–—]\s*(?<end>\d{4}|Present|Current)", RegexOptions.IgnoreCase);
            if (!dates.Success) continue;

            var identity = Regex.Replace(line, @"\s*[|,(]?\s*\d{4}\s*[-–—]\s*(?:\d{4}|Present|Current)\s*\)?\s*$", string.Empty, RegexOptions.IgnoreCase).Trim();
            var parts = Regex.Split(identity, @"\s+(?:—|–|\||at)\s+", RegexOptions.IgnoreCase);
            if (parts.Length != 2 || parts.Any(string.IsNullOrWhiteSpace)) continue;

            roles.Add(new StructuredCvJob
            {
                Title = parts[0].Trim(),
                Company = parts[1].Trim(),
                Start = dates.Groups["start"].Value,
                End = dates.Groups["end"].Value,
                IsCurrent = dates.Groups["end"].Value.Equals("Present", StringComparison.OrdinalIgnoreCase)
                    || dates.Groups["end"].Value.Equals("Current", StringComparison.OrdinalIgnoreCase),
            });
        }
        return roles;
    }

    private static string? TitleCasePreservingAcronyms(string? value)
    {
        if (string.IsNullOrWhiteSpace(value)) return null;

        var words = value.Trim()
            .Split(' ', StringSplitOptions.RemoveEmptyEntries)
            .Select(word => word.Length <= 3 && word.All(char.IsUpper)
                ? word
                : char.ToUpperInvariant(word[0]) + word[1..].ToLowerInvariant())
            .ToArray();

        return string.Join(" ", words);
    }

    private static string? InferQualificationLevel(string? value)
    {
        var candidate = value?.Trim();
        if (string.IsNullOrWhiteSpace(candidate)) return null;
        if (Regex.IsMatch(candidate, @"\b(phd|doctorate|dphil)\b", RegexOptions.IgnoreCase)) return "PhD";
        if (Regex.IsMatch(candidate, @"\b(master(?:'s)?|msc|m\.sc|ma|m\.a|mba|meng)\b", RegexOptions.IgnoreCase)) return "Master";
        if (Regex.IsMatch(candidate, @"\b(bachelor(?:'s)?|bsc|b\.sc|ba|b\.a|beng|degree)\b", RegexOptions.IgnoreCase)) return "Bachelor";
        if (Regex.IsMatch(candidate, @"\b(diploma|certificate|certification|nvq|btec|level\s*\d+|apprenticeship|associate)\b", RegexOptions.IgnoreCase)) return "Diploma/Certificate";
        if (Regex.IsMatch(candidate, @"\b(gcse|a-?level|secondary|high school)\b", RegexOptions.IgnoreCase)) return "Secondary";
        return "Other";
    }

    private static int CountWords(string? text)
    {
        if (string.IsNullOrWhiteSpace(text)) return 0;
        return text.Trim().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Length;
    }

    private static string? NullIfWhitespace(string? value)
    {
        return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
    }

    private static List<(string Name, string Content)> ParseSections(string source)
    {
        var lines = source.Replace("\r\n", "\n").Split('\n');
        var sections = new List<(string Name, List<string> Lines)>();
        var currentName = "General";
        var currentLines = new List<string>();

        void Flush()
        {
            var content = string.Join("\n", currentLines).Trim();
            if (!string.IsNullOrWhiteSpace(content))
            {
                sections.Add((currentName, new List<string>(currentLines)));
            }
            currentLines.Clear();
        }

        foreach (var raw in lines)
        {
            var line = raw.Trim();
            var sectionHeading = CanonicalizeSectionHeading(line) ?? DetectCustomSectionHeading(line);
            if (sectionHeading is not null)
            {
                Flush();
                currentName = sectionHeading;
                continue;
            }

            currentLines.Add(raw);
        }

        Flush();

        if (sections.Count == 0)
        {
            return new List<(string Name, string Content)> { ("General", source.Trim()) };
        }

        return sections
            .Select(section => (section.Name, string.Join("\n", section.Lines).Trim()))
            .Where(section => !string.IsNullOrWhiteSpace(section.Item2))
            .ToList();
    }

    private static List<StructuredCvSection> BuildSectionsFromClassifiedBlocks(List<ClassifiedCvBlock> classifiedBlocks)
    {
        var sectionBuckets = new List<StructuredCvSection>();
        foreach (var block in classifiedBlocks)
        {
            var existing = sectionBuckets.FirstOrDefault(section => section.Name == block.SectionName);
            if (existing is null)
            {
                sectionBuckets.Add(new StructuredCvSection { Name = block.SectionName, Content = block.Content, WordCount = CountWords(block.Content) });
            }
            else
            {
                existing.Content = $"{existing.Content}\n\n{block.Content}".Trim();
                existing.WordCount = CountWords(existing.Content);
            }
        }

        return sectionBuckets.Where(section => !string.IsNullOrWhiteSpace(section.Content)).ToList();
    }

    private static StructuredCvProfile BuildStructuredCvFromClassifiedBlocks(List<ClassifiedCvBlock> classifiedBlocks)
    {
        var profile = new StructuredCvProfile();
        var now = DateTimeOffset.UtcNow;
        var summary = new List<string>();
        var skills = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

        foreach (var block in classifiedBlocks)
        {
            switch (block.SectionName)
            {
                case "Professional Summary":
                    foreach (var item in (block.Classification?.Summary is { Count: > 0 }
                        ? block.Classification.Summary
                        : SplitClassifierContent(block.Content, 5)))
                    {
                        summary.Add(item);
                    }
                    ApplyClassifierFieldMetadata(profile, "summary", summary.FirstOrDefault(), block, now);
                    break;
                case "Skills":
                    foreach (var item in (block.Classification?.Skills is { Count: > 0 }
                        ? block.Classification.Skills.Where(skill => !string.IsNullOrWhiteSpace(skill)).Select(skill => skill.Trim())
                        : SplitClassifierSkills(block.Content)))
                    {
                        skills.Add(item);
                    }
                    ApplyClassifierFieldMetadata(profile, "skills", skills.FirstOrDefault(), block, now);
                    break;
                case "Work Experience":
                    var job = BuildJobFromClassifiedBlock(block);
                    if (job is not null)
                    {
                        var index = profile.Jobs.Count;
                        profile.Jobs.Add(job);
                        ApplyClassifierFieldMetadata(profile, $"jobs[{index}].title", job.Title, block, now);
                        ApplyClassifierFieldMetadata(profile, $"jobs[{index}].company", job.Company, block, now);
                        ApplyClassifierFieldMetadata(profile, $"jobs[{index}].location", job.Location, block, now);
                    }
                    break;
                case "Education":
                    var education = BuildEducationFromClassifiedBlock(block);
                    if (education is not null)
                    {
                        var index = profile.Education.Count;
                        profile.Education.Add(education);
                        ApplyClassifierFieldMetadata(profile, $"education[{index}].qualification", education.Qualification, block, now);
                        ApplyClassifierFieldMetadata(profile, $"education[{index}].institution", education.Institution, block, now);
                    }
                    break;
                default:
                    if (!string.IsNullOrWhiteSpace(block.Content))
                    {
                        profile.OtherSections.Add(new StructuredCvOtherSection
                        {
                            Title = block.SectionName,
                            Items = SplitClassifierContent(block.Content, 6)
                        });
                    }
                    break;
            }
        }

        profile.Summary = summary.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
        profile.Skills = skills.ToList();
        profile.Sections = BuildSectionsFromClassifiedBlocks(classifiedBlocks);

        var averageConfidence = classifiedBlocks
            .Select(block => block.Classification?.Confidence)
            .Where(value => value.HasValue)
            .Select(value => value!.Value)
            .DefaultIfEmpty(0.74)
            .Average();
        AnnotateStructuredCv(profile, "classifier", averageConfidence);
        return StructuredCvProfileJson.Normalize(profile);
    }

    private static StructuredCvJob? BuildJobFromClassifiedBlock(ClassifiedCvBlock block)
    {
        var classification = block.Classification;
        if (classification is null) return null;

        var bullets = classification.Bullets is { Count: > 0 }
            ? classification.Bullets.Where(bullet => !string.IsNullOrWhiteSpace(bullet)).Select(bullet => bullet.Trim()).ToList()
            : SplitClassifierContent(block.OriginalBlock, 6);

        var job = new StructuredCvJob
        {
            Title = NullIfWhitespace(classification.Title),
            Company = NullIfWhitespace(classification.Company),
            Location = NullIfWhitespace(classification.Location),
            Start = NullIfWhitespace(classification.Start),
            End = NullIfWhitespace(classification.End),
            IsCurrent = string.Equals(classification.End, "Present", StringComparison.OrdinalIgnoreCase) || string.Equals(classification.End, "Current", StringComparison.OrdinalIgnoreCase),
            Bullets = bullets,
            Skills = classification.Skills is { Count: > 0 }
                ? classification.Skills.Where(skill => !string.IsNullOrWhiteSpace(skill)).Select(skill => skill.Trim()).ToList()
                : SplitClassifierSkills(block.OriginalBlock)
        };

        return StructuredCvProfileJson.Normalize(new StructuredCvProfile { Jobs = new List<StructuredCvJob> { job } }).Jobs.FirstOrDefault();
    }

    private static StructuredCvEducation? BuildEducationFromClassifiedBlock(ClassifiedCvBlock block)
    {
        var classification = block.Classification;
        if (classification is null) return null;

        var education = new StructuredCvEducation
        {
            Qualification = NullIfWhitespace(classification.Title),
            Institution = NullIfWhitespace(classification.Company),
            Location = NullIfWhitespace(classification.Location),
            Start = NullIfWhitespace(classification.Start),
            End = NullIfWhitespace(classification.End),
            Details = classification.Bullets is { Count: > 0 }
                ? classification.Bullets.Where(bullet => !string.IsNullOrWhiteSpace(bullet)).Select(bullet => bullet.Trim()).ToList()
                : SplitClassifierContent(block.OriginalBlock, 5)
        };

        return StructuredCvProfileJson.Normalize(new StructuredCvProfile { Education = new List<StructuredCvEducation> { education } }).Education.FirstOrDefault();
    }

    private static List<string> SplitClassifierContent(string content, int limit)
    {
        return content
            .Replace("\r\n", "\n")
            .Split(new[] { '\n', '•' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
            .SelectMany(line => line.Contains(". ", StringComparison.Ordinal)
                ? Regex.Split(line, @"(?<=[.!?])\s+")
                : new[] { line })
            .Select(item => item.Trim().TrimStart('-', '•', '*', '+', ' '))
            .Where(item => item.Length > 2)
            .Take(limit)
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .ToList();
    }

    private static List<string> SplitClassifierSkills(string content)
    {
        return content
            .Replace("\r\n", "\n")
            .Split(new[] { '\n', ',', ';', '•' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
            .Select(item => item.Trim().TrimStart('-', '•', '*', '+', ' '))
            .Where(item => item.Length > 1 && item.Length <= 48 && !LooksLikeDateLikeValue(item) && !item.Contains('@'))
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .ToList();
    }

    private static bool LooksLikeDateLikeValue(string value)
    {
        return Regex.IsMatch(value, @"^(?:\d{4}|(?:Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|Sept|September|Oct|October|Nov|November|Dec|December)\s+\d{4}|Present|Current)(?:\s*[-–]\s*(?:\d{4}|(?:Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|Sept|September|Oct|October|Nov|November|Dec|December)\s+\d{4}|Present|Current))?$", RegexOptions.IgnoreCase);
    }

    private static void ApplyClassifierFieldMetadata(StructuredCvProfile profile, string key, string? value, ClassifiedCvBlock block, DateTimeOffset now)
    {
        if (string.IsNullOrWhiteSpace(value)) return;

        profile.Metadata.Fields[key] = new StructuredCvFieldMetadata
        {
            Confidence = block.Classification?.Confidence ?? 0.74,
            Method = "classifier",
            SourceSnippet = block.OriginalBlock.Length > 180 ? block.OriginalBlock[..180] : block.OriginalBlock,
            SourceBlockId = $"block-{block.Index}",
            ReviewState = string.Equals(block.SectionName, "General", StringComparison.OrdinalIgnoreCase) ? "needs-review" : "suggested",
            LastUpdatedAtUtc = now,
        };
    }

    private async Task<List<ClassifiedCvBlock>> ClassifyBlocksAsync(string parseSource, CancellationToken cancellationToken)
    {
        var blocks = Regex.Split(parseSource.Replace("\r\n", "\n"), @"\n\s*\n")
            .Select(block => block.Trim())
            .Where(block => block.Length >= 24)
            .ToList();

        if (blocks.Count == 0) return new List<ClassifiedCvBlock>();

        var results = new List<ClassifiedCvBlock>();
        for (var index = 0; index < blocks.Count; index++)
        {
            var block = blocks[index];
            var classification = await _cvAiClassifier.ClassifyBlockAsync(block, cancellationToken);
            var sectionName = classification?.Section;
            if (!string.IsNullOrWhiteSpace(sectionName) && SectionAliases.TryGetValue(sectionName, out var canonical))
            {
                sectionName = canonical;
            }

            if (string.IsNullOrWhiteSpace(sectionName) || string.Equals(sectionName, "Other", StringComparison.OrdinalIgnoreCase))
            {
                sectionName = "General";
            }

            var content = block;
            if (string.Equals(sectionName, "Work Experience", StringComparison.OrdinalIgnoreCase) && classification is not null)
            {
                var lines = new List<string>();
                if (!string.IsNullOrWhiteSpace(classification.Title)) lines.Add($"### {classification.Title.Trim()}");
                var endIsCurrent = string.Equals(classification.End, "Present", StringComparison.OrdinalIgnoreCase) || string.Equals(classification.End, "Current", StringComparison.OrdinalIgnoreCase);
                var dateRange = FormatDateRangeForSection(classification.Start, classification.End, endIsCurrent);
                var meta = string.Join(" | ", new[] { classification.Company, classification.Location, dateRange }.Where(value => !string.IsNullOrWhiteSpace(value)));
                if (!string.IsNullOrWhiteSpace(meta)) lines.Add(meta);
                if (classification.Bullets is not null)
                {
                    lines.AddRange(classification.Bullets.Where(bullet => !string.IsNullOrWhiteSpace(bullet)).Select(bullet => $"- {bullet.Trim()}"));
                }
                if (lines.Count > 0) content = string.Join("\n", lines);
            }
            else if (string.Equals(sectionName, "Education", StringComparison.OrdinalIgnoreCase) && classification is not null)
            {
                var lines = new List<string>();
                if (!string.IsNullOrWhiteSpace(classification.Title)) lines.Add($"### {classification.Title.Trim()}");
                var dateRange = FormatDateRangeForSection(classification.Start, classification.End, false);
                var meta = string.Join(" | ", new[] { classification.Company, classification.Location, dateRange }.Where(value => !string.IsNullOrWhiteSpace(value)));
                if (!string.IsNullOrWhiteSpace(meta)) lines.Add(meta);
                if (classification.Bullets is not null)
                {
                    lines.AddRange(classification.Bullets.Where(bullet => !string.IsNullOrWhiteSpace(bullet)).Select(bullet => $"- {bullet.Trim()}"));
                }
                if (lines.Count > 0) content = string.Join("\n", lines);
            }
            else if (string.Equals(sectionName, "Skills", StringComparison.OrdinalIgnoreCase))
            {
                var items = classification?.Skills is { Count: > 0 }
                    ? classification.Skills.Where(skill => !string.IsNullOrWhiteSpace(skill)).Select(skill => skill.Trim()).ToList()
                    : SplitClassifierSkills(block);
                if (items.Count > 0) content = string.Join("\n", items);
            }
            else if (string.Equals(sectionName, "Professional Summary", StringComparison.OrdinalIgnoreCase))
            {
                var items = classification?.Summary is { Count: > 0 }
                    ? classification.Summary.Where(line => !string.IsNullOrWhiteSpace(line)).Select(line => $"- {line.Trim()}")
                    : classification?.Bullets is { Count: > 0 }
                        ? classification.Bullets.Where(bullet => !string.IsNullOrWhiteSpace(bullet)).Select(bullet => $"- {bullet.Trim()}")
                        : Enumerable.Empty<string>();
                var materialized = items.ToList();
                if (materialized.Count > 0) content = string.Join("\n", materialized);
            }

            results.Add(new ClassifiedCvBlock(index + 1, block, sectionName, content, classification));
        }

        return results;
    }

    private static string? FormatDateRangeForSection(string? start, string? end, bool isCurrent)
    {
        if (string.IsNullOrWhiteSpace(start) && string.IsNullOrWhiteSpace(end)) return null;
        if (string.IsNullOrWhiteSpace(start)) return end;
        return $"{start} - {(isCurrent ? "Present" : end ?? "Present")}";
    }

    private async Task<string> MaybeReconstructStructuredCvAsync(string text, CancellationToken cancellationToken)
    {
        var normalized = text.Trim();
        var forceAiNormalizer = string.Equals(Environment.GetEnvironmentVariable("CV_FORCE_AI_NORMALIZER"), "true", StringComparison.OrdinalIgnoreCase);
        if (forceAiNormalizer)
        {
            var forced = await _cvAiNormalizer.NormalizeAsync(normalized, cancellationToken);
            if (!string.IsNullOrWhiteSpace(forced?.NormalizedText))
            {
                return forced.NormalizedText.Trim();
            }
        }

        var looksFlattened = LooksLikeFlattenedCvExtraction(normalized);
        var hasRecoverableSignals = HasRecoverableSectionSignals(normalized);

        if (!looksFlattened && hasRecoverableSignals)
        {
            return normalized;
        }

        var reconstructed = await _aiService.SummarizeSectionAsync(
            "Reconstruct this CV text extracted from a PDF into a clean, readable master CV in markdown. Preserve facts only. Recover clear sections such as Contact, Professional Summary, Work Experience, Education, Skills, Languages, and Interests when present. Split contact details onto their own lines, turn noisy all-caps/spaced headings into normal headings, keep dates with the correct roles and employers, and remove layout/OCR artifacts. Do not invent employers, titles, dates, or metrics. Return only the reconstructed CV text.",
            normalized,
            2800,
            900);

        var candidate = string.IsNullOrWhiteSpace(reconstructed) ? normalized : reconstructed.Trim();
        if (LooksLikeFlattenedCvExtraction(candidate) || !HasRecoverableSectionSignals(candidate))
        {
            var aiNormalized = await _cvAiNormalizer.NormalizeAsync(normalized, cancellationToken);
            if (!string.IsNullOrWhiteSpace(aiNormalized?.NormalizedText))
            {
                return aiNormalized.NormalizedText.Trim();
            }
        }

        return candidate;
    }

    private static bool LooksLikeFlattenedCvExtraction(string text)
    {
        if (string.IsNullOrWhiteSpace(text)) return false;

        var normalized = text.Replace("\r\n", "\n");
        var lineCount = normalized.Split('\n').Count(line => !string.IsNullOrWhiteSpace(line));
        var spacedHeadingCount = Regex.Matches(normalized, @"\b(?:[A-Z]\s){3,}[A-Z]\b").Count;
        var knownHeadingHits = SectionAliases.Keys.Count(alias => normalized.Contains(alias, StringComparison.OrdinalIgnoreCase));
        var bulletCount = Regex.Matches(normalized, @"[•●▪◦]").Count;

        return (lineCount <= 6 && normalized.Length >= 500)
            || spacedHeadingCount >= 3
            || (knownHeadingHits >= 3 && lineCount <= 12)
            || (normalized.Contains(" + ") && bulletCount > 0 && lineCount <= 10);
    }

    private static bool LooksLikeNormalizedMarkdownCv(string text)
    {
        if (string.IsNullOrWhiteSpace(text)) return false;
        return Regex.IsMatch(text, @"(?im)^#\s+(Contact|Professional Summary|Work Experience|Education|Skills|Languages|Interests|Projects|Certifications)\s*$");
    }

    private static StructuredCvProfile BuildStructuredCvFromNormalizedMarkdown(string text)
    {
        text = SeparateGluedDateAndTitle(text);
        var sections = ParseSections(text)
            .Select(section => new StructuredCvSection
            {
                Name = section.Name,
                Content = section.Content,
                WordCount = CountWords(section.Content),
            })
            .ToList();

        var profile = StructuredCvProfileJson.FromSections(sections);
        profile.Sections = sections;
        var workExperience = sections.FirstOrDefault(section => section.Name == "Work Experience")?.Content;
        if (!string.IsNullOrWhiteSpace(workExperience))
        {
            profile.Jobs.RemoveAll(job => (job.Title ?? string.Empty).StartsWith("Earlier roles", StringComparison.OrdinalIgnoreCase));
            foreach (var role in ParseEarlierRoles(workExperience))
            {
                if (!profile.Jobs.Any(job => string.Equals(job.Title, role.Title, StringComparison.OrdinalIgnoreCase)
                    && string.Equals(job.Company, role.Company, StringComparison.OrdinalIgnoreCase))) profile.Jobs.Add(role);
            }
        }

        if (string.IsNullOrWhiteSpace(profile.Contact.FullName))
        {
            profile.Contact.FullName = GuessFullName(text) ?? GuessFullNameFromEmail(profile.Contact.Email);
        }

        var contactSection = sections.FirstOrDefault(section => section.Name == "Contact");
        profile.Contact.Location = PreferDetectedLocation(contactSection?.Content ?? text, profile.Contact.Location, profile.Contact.FullName);
        profile.Summary = CondenseSummary(profile.Summary);
        profile.Skills = OrderSkills(profile.Skills);
        profile.Interests = CleanInterestItems(profile.Interests);

        foreach (var job in profile.Jobs)
        {
            job.Bullets = job.Bullets.Where(bullet => !bullet.Contains("Detail not specified", StringComparison.OrdinalIgnoreCase)).ToList();
        }

        foreach (var education in profile.Education)
        {
            education.Details = education.Details.Where(detail => !detail.Contains("Detail not specified", StringComparison.OrdinalIgnoreCase)).ToList();
        }

        return profile;
    }

    private static List<string> CondenseSummary(List<string> summary)
    {
        if (summary.Count <= 1) return summary;
        var joined = string.Join(" ", summary).Trim();
        return string.IsNullOrWhiteSpace(joined) ? new List<string>() : new List<string> { joined };
    }

    private static List<string> OrderSkills(List<string> skills)
    {
        return skills
            .Select(CleanSkillGroupPrefix)
            .Where(skill => skill.Length > 0)
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .OrderBy(skill => skill, StringComparer.OrdinalIgnoreCase)
            .ToList();
    }

    private static string CleanSkillGroupPrefix(string skill)
        => Regex.Replace(skill.Trim(), @"^(?:Development|Programming Languages?|Backend|Frontend|Databases?|DevOps(?:\s*(?:&|og)\s*(?:CI/CD|Infrastructure))?|Infrastructure|Operations|Practices|Tools|Technologies|Technical Skills|Programmeringsspråk|Databaser|Infrastruktur|Drift|Praksis|Metodikk)\s*:\s*", string.Empty, RegexOptions.IgnoreCase).Trim();

    private static string SeparateGluedDateAndTitle(string text)
        => Regex.Replace(text, @"(?<date>\b\d{4}\s*[-–—]\s*(?:\d{4}|Present|Current))(?<title>[\p{L}][^\r\n]*)", "${title}\n${date}", RegexOptions.IgnoreCase);

    private static string RepairKnownMojibake(string text)
        => text
            .Replace("Ã¸", "ø", StringComparison.Ordinal)
            .Replace("Ã˜", "Ø", StringComparison.Ordinal)
            .Replace("Ã¦", "æ", StringComparison.Ordinal)
            .Replace("Ã†", "Æ", StringComparison.Ordinal)
            .Replace("Ã¥", "å", StringComparison.Ordinal)
            .Replace("Ã…", "Å", StringComparison.Ordinal)
            .Replace("â€“", "–", StringComparison.Ordinal)
            .Replace("â€”", "—", StringComparison.Ordinal)
            .Replace("â€™", "’", StringComparison.Ordinal)
            .Replace("â€œ", "“", StringComparison.Ordinal)
            .Replace("â€", "”", StringComparison.Ordinal);

    private static List<string> CleanInterestItems(List<string> interests)
    {
        return interests
            .Where(item => !item.Contains("linkedin", StringComparison.OrdinalIgnoreCase)
                && !item.Contains("realtor", StringComparison.OrdinalIgnoreCase)
                && !Regex.IsMatch(item, @"https?://|www\.", RegexOptions.IgnoreCase))
            .ToList();
    }

    private static string? CanonicalizeSectionHeading(string line)
    {
        if (string.IsNullOrWhiteSpace(line)) return null;

        var normalized = line.Trim();
        if (normalized.StartsWith("#", StringComparison.Ordinal))
        {
            normalized = normalized.TrimStart('#').Trim();
        }

        normalized = Regex.Replace(normalized, @"^\s*\d{1,2}\s*(?:[-–—.:)]\s*)+", string.Empty).Trim();
        normalized = Regex.Replace(normalized, @"\s+", " ").TrimEnd(':').Trim();
        if (normalized.Length == 0 || normalized.Length > 60) return null;
        if (normalized.Contains('.') || normalized.Contains("  ")) return null;

        return SectionAliases.TryGetValue(normalized, out var canonical) ? canonical : null;
    }

    private static string? DetectCustomSectionHeading(string line)
    {
        if (string.IsNullOrWhiteSpace(line)) return null;
        var markdown = line.TrimStart().StartsWith("#", StringComparison.Ordinal);
        var candidate = line.Trim().TrimStart('#').Trim();
        candidate = Regex.Replace(candidate, @"^\s*\d{1,2}\s*(?:[-–—.:)]\s*)+", string.Empty).Trim().TrimEnd(':').Trim();
        if (candidate.Length is < 3 or > 60 || candidate.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length > 7) return null;
        if (Regex.IsMatch(candidate, @"\d{4}|@|https?://|www\.|^[•+*-]")) return null;
        var letters = candidate.Where(char.IsLetter).ToArray();
        // A lone all-caps token is commonly a skill (SQL, AWS, DOCKER), not a new section.
        // Unknown single-word headings remain available through explicit Markdown headings.
        var upperHeading = letters.Length >= 3 && letters.All(char.IsUpper) && candidate.Contains(' ');
        if (!markdown && !upperHeading) return null;
        return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(candidate.ToLowerInvariant());
    }

    private static bool HasRecoverableSectionSignals(string text)
    {
        var sections = ParseSections(text);
        return sections.Any(section => !string.Equals(section.Name, "General", StringComparison.OrdinalIgnoreCase))
            || Regex.IsMatch(text, @"(?im)^\s*(Contact|Professional Summary|Summary|Work Experience|Experience|Education|Skills|Languages|Interests)\s*:?")
            || Regex.IsMatch(text, @"(?im)^\s*#\s*(Contact|Professional Summary|Summary|Work Experience|Experience|Education|Skills|Languages|Interests)");
    }

    private static async Task<string> ExtractPlainTextAsync(IFormFile file, string extension, CancellationToken cancellationToken)
    {
        if (!string.Equals(extension, ".txt", StringComparison.OrdinalIgnoreCase) &&
            !string.Equals(extension, ".md", StringComparison.OrdinalIgnoreCase)) return string.Empty;

        using var stream = file.OpenReadStream();
        using var reader = new StreamReader(
            stream,
            new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true),
            detectEncodingFromByteOrderMarks: true);
        var buffer = new char[8192];
        var result = new StringBuilder(capacity: (int)Math.Min(file.Length, 64 * 1024));
        while (true)
        {
            var read = await reader.ReadAsync(buffer.AsMemory(), cancellationToken);
            if (read == 0) break;
            if (result.Length + read > 200_000)
            {
                throw new InvalidOperationException("The extracted CV text is too large to process safely.");
            }
            result.Append(buffer, 0, read);
        }

        return result.ToString().Trim();
    }
}
