package parser

import (
	"bufio"
	"os"
	"regexp"
	"strings"
)

// Policy represents a policy rule from instruction files
// Simplified: No types or patterns, all detection is LLM-based
type Policy struct {
	Name         string
	Message      string
	OriginalText string
}

// ParseAgents parses AGENTS.md content and extracts enforceable policies
func ParseAgents(content string) ([]Policy, error) {
	var policies []Policy
	scanner := bufio.NewScanner(strings.NewReader(content))

	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())

		// Skip empty lines and headers
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}

		// Look for bullet points or numbered lists
		if strings.HasPrefix(line, "-") || strings.HasPrefix(line, "*") || regexp.MustCompile(`^\d+\.`).MatchString(line) {
			// Remove list markers
			line = regexp.MustCompile(`^[-*\d.]\s*`).ReplaceAllString(line, "")

			if policy := parsePolicy(line); policy != nil {
				policies = append(policies, *policy)
			}
		}
	}

	return policies, scanner.Err()
}

// ParseAgentsFile reads an AGENTS.md file and extracts enforceable policies
// NOTE: This uses the old regex-based extraction. Use extractor.ExtractPoliciesFromFile for LLM-based extraction.
func ParseAgentsFile(filepath string) ([]Policy, error) {
	content, err := os.ReadFile(filepath)
	if err != nil {
		return nil, err
	}

	return ParseAgents(string(content))
}

// parsePolicy attempts to convert a policy statement into a policy
// Legacy regex-based parsing - kept for backwards compatibility
// Prefer using extractor.ExtractPoliciesFromFile for better accuracy
func parsePolicy(text string) *Policy {
	return &Policy{
		Name:         text, // Use the policy text as the name
		Message:      text,
		OriginalText: text,
	}
}

