import Foundation
import UIKit

/// How a clip's video data is referenced. Never copied — see plan's two-layer data model.
enum SourceKind: String, Codable {
    /// A file on disk (external drive, Files app) referenced via a security-scoped bookmark.
    case file
    /// A clip inside the Photos library, referenced by PHAsset local identifier.
    case photos
}

struct SourceRef: Codable {
    var kind: SourceKind
    var bookmarkData: Data?
    var photosAssetID: String?
}

/// Lightweight identity metadata captured at import time, used to re-find a clip
/// after its reference breaks (e.g. exported out of Photos onto a drive).
struct ClipFingerprint: Codable, Equatable {
    var duration: Double
    var pixelWidth: Int
    var pixelHeight: Int
    var fileSize: Int64?
    var creationDate: Date?
}

struct SourceClip: Identifiable, Codable {
    let id: UUID
    var displayName: String
    var ref: SourceRef
    var fingerprint: ClipFingerprint
    var addedAt: Date
    /// Set when the clip is relinked, so a bad match can be reverted.
    var previousRef: SourceRef?
    /// Debug-only: pretend the reference is broken to exercise the relink flow.
    var debugBroken: Bool?

    var isDebugBroken: Bool { debugBroken ?? false }
}

/// A folder the user granted access to once; the app can silently rescan it later.
struct GrantedFolder: Identifiable, Codable {
    let id: UUID
    var bookmarkData: Data
    var displayName: String
}

enum ClipAvailability: Equatable {
    case unknown
    case available
    case missing(reason: String)
}

/// A file found during a relink scan that fingerprint-matches a broken clip.
struct RelinkCandidate: Identifiable {
    let id = UUID()
    var fileURL: URL
    var folderID: UUID
    var fingerprint: ClipFingerprint
    var score: Double
    var thumbnail: UIImage?
    /// False when the matched file is shorter than the original — trims past its
    /// end would break, so the confirmation UI must flag it.
    var isDurationSufficient: Bool

    var isStrongMatch: Bool { score >= 0.8 }
}
